C ++:带有空格的cin到没有getline函数的字符串
C++: cin with white spaces to strings without getline function
我正在做一个看起来像学生数据库的大学项目。
文本文件的每一行都遵循 "model":
age ; full_name ; avg
我需要读取文本文件并将所有内容存储在一个结构向量中,如果名称只有一个单词,我就可以做到这一点。
很明显,age 是一个 int,avg 是一个 double,但是全名呢?
我不能只使用 file >> full_name;
,而 full_name 是一个字符串,因为一旦它到达空格就会停止读取它。 getline()
函数会将所有内容存储在一个地方,所以我不知道该怎么做。
请与这个年轻的头脑分享您的知识 x)
正如许多其他人指出的那样,您可以使用 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';
}
我正在做一个看起来像学生数据库的大学项目。 文本文件的每一行都遵循 "model":
age ; full_name ; avg
我需要读取文本文件并将所有内容存储在一个结构向量中,如果名称只有一个单词,我就可以做到这一点。
很明显,age 是一个 int,avg 是一个 double,但是全名呢?
我不能只使用 file >> full_name;
,而 full_name 是一个字符串,因为一旦它到达空格就会停止读取它。 getline()
函数会将所有内容存储在一个地方,所以我不知道该怎么做。
请与这个年轻的头脑分享您的知识 x)
正如许多其他人指出的那样,您可以使用 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';
}