简体   繁体   中英

C++ - Using stringstream object to read strings and integers from a sentence in an external txt file

I tried to retrieve the integers from a txt file and adding them up to get the total. I did this using stringstream class. The string of the text is:- 100 90 80 70 60 . The code to extract the integers and add them is as follows:-

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
    ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
    stringstream sstr;
    string from_file;
    int grade;
    int total = 0;
    getline(inFile,from_file);
    sstr<<from_file;
    while(sstr
    {
        sstr>>grade;
        cout<<grade<<endl;
        total+=grade;
    }
    cout<<total<<endl;
    inFile.close();
    return 0;
}

This code works fine. After this, I modify the string in the file as 'the grades you scored are 100 90 80 70 60`. Now, if try to run the above code, I get the output as:-

0
0
0
0
0
0

Can you please help me and tell me how to calculate the total in the latter case ? Also, here I know the number of integers in the files. What about the case when I don't know the number of grades in the file?

Because "the grades you scored are " is the head part of your stringstream.

You cannot get read an int from it. It'll just give you a 0

You may read to some string as "Entry" and parse the Entry by writing some functions.

I'll be answering the second part of the question ie reading inputs without knowing the total number of inputs:-

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
    ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
    string data;
    int grades,total=0;
    getline(inFile,data);
    stringstream sstr;
    sstr<<data;
    while(true)
    {
        sstr>>grades;   
        if(!sstr)
            break;
        cout<<grades<<endl;
        total+=grades;
    }
    cout<<total<<endl;
    return 0;
}

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