简体   繁体   中英

Trying to parse a line read from an input file

I have a problem regarding reading input lines from a file. Which is quite a simple task I can manage but the problem is input file lines can consist of words and numbers which then I have to read them seperately and store them in different variables. Let me give an example(italics):

BOOK 100
PENCIL      45
LAPTOP   49
SPOON             34

The reading operation would work regardless of how many spaces there between the Word and the numbers.

I have written this piece of code to read lines directly. But I do not know how to parse them according to the information I gave up.

string fileName;
        cout << "Enter the name of the file: ";
        cin >> fileName;

        ifstream file;
        file.open(fileName);

        while(file.fail())
        {
            cout << "enter file name correctly:";
            cin >> fileName;
            file.open(fileName);
        }

        string line;
        int points;


        while(!file.eof())
        {
            getline(file, line);
            stringstream ss(line);

                    *I do not know what to do here :)*
                    }

But I do not know how to parse them according to the information I gave up.

Thats quite simple, see below example:

std::stringstream ss("SPOON             34");
std::string s;
int n;
if (ss >> s >> n) {
    std::cout << s <<"\n";
    std::cout << n <<"\n";
}

outputs:

SPOON
34

You can use sscanf .

char name[100];
int number;
sscanf(line, "%s %d", name, &number);
printf("%s, %d", name, number);

Now I am not sure if this really C++ish. The alternative being using stringstreams like you have started.

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