C ++:带有空格的cin,没有getline函数的字符串

时间:2016-03-23 18:00:18

标签: c++ string file whitespace getline

我正处于大学项目的中间,这看起来像学生的数据库。 文本文件的每一行都遵循这个“模型”:

 age ; full_name ; avg

我需要读取文本文件并将所有内容存储在结构体的向量中,如果名称只有一个单词,我可以这样做。 好吧,显然,年龄是一个int,平均是一个双倍,但全名呢? 我不能只使用file >> full_name;,而full_name是一个字符串,因为它一旦到达空格就会停止读取它。 getline()函数会将所有内容存储在一个地方,所以我不知道该怎么做。

请与这位年轻的心灵分享你的知识x)

1 个答案:

答案 0 :(得分:1)

正如许多其他人指出的那样,您可以使用std::getline来读取字符直到分隔符。

将这段代码视为一个起点:

int age;
std::string name;
double average;

// ... Open the file which stores the data ... 

// then read every line. The loop stops if some of the reading operations fails
while ( input >> age  && 
        std::getline(input, name, ';')  &&        // consume the first ;
        std::getline(input, name, ';')  &&        // read the name
        input >> average ) {
    // do whatever you need with the data read
    cout << "age: " << age << " name: " << name << " average: " << average << '\n';
}
相关问题