简体   繁体   English

C ++-使用stringstream对象从外部txt文件中的句子中读取字符串和整数

[英]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. 我试图从txt文件中检索整数并将它们加起来以获得总数。 I did this using stringstream class. 我使用stringstream类完成了此操作。 The string of the text is:- 100 90 80 70 60 . 文本字符串为: 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`. 之后,我将文件中的字符串修改为“您的分数是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. 您无法从中读取一个int。 It'll just give you a 0 它只会给你0

You may read to some string as "Entry" and parse the Entry by writing some functions. 您可以阅读一些字符串作为“ Entry”,并通过编写一些函数来解析Entry。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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