简体   繁体   中英

C++ Is there a way to get getline to read 2 numbers in a line separated by a space?

I need my program to read these numbers:

4
42 5
47 6

This is what I've got so far:

//5sk3u
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int f,d,s; //f=4, d=42, then 47, s=5, then 6
    string line;
    ifstream myf ("Data.txt");
    (getline (myf,line));
    f=std::stod (line);
    getline (myf,line);
    d=std::stod(line);
    getline (myf,line);
    s=std::stod(line);
    cout << f << endl;
    cout << d << endl;
    cout << s;         //I'll make a loop for the final program, but right now this part isn't working
}

I don't understand how to get s=5 instead of s=47. I'm new to this and by reading through other solutions I couldn't understand anything, since there was too much new info. What's the easiest way to do this that's close to my existent code? Thanks for the help.

Edit: Here is my task."Chickens are being sold at a market. The chicken data is written in the file "Data.txt" with the number of chickens for sale on the first line and the subsequent lines showing the chicken's mass and age. Write a program that will find and print the original chicken's data in the results file "Results.txt"." The result needs to look like this: "Chicken numbr.1: mass:42 age:5" and so on for all the chickens.

If this is some online problem solver do not make this over-complicated. Just read this this way:

int main()
{
     int n, age, mass;
     std::ifstream chickensFile("Data.txt");
     chickensFile >> n;

     for(int i=0; i < n; ++i) {
         chickensFile >> mass >> age;
         std:cout << "Chicken numbr: "<< /* do it yourself */;
     }

     return 0;
}

You can read words that are separated with whitespace from file like this:

    ifstream file("Data.txt");
    std::string word;
    while (file >> word)
    {
        std::cout<< word << '\n';
    }

Asked my friend and we made this together:

int a,x,z,n,f,j;
fstream fd;
fd.open ("Duomenys.txt");
n=0;
f=0;
j=z+1;
fd >> a;
while (n<a){
fd >> x >> z;
cout << x << " " << z << endl;
if (x>f){f=x;}
if (z<j){j=z;}
n++;}
cout << f << endl;
cout << z;

Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM