我想知道在尝试为名称分配值时是否有任何方法不忽略空格。
我想在 while 循环中保留这个条件结构*,但像 getline 一样获取 ClientFile >> 而不是 cin。
*我知道我可以使用子字符串并查找,但这不是想法。
文本文件中的行示例:
1 ; Iron Man ; 10.70
问题: 程序不会进入循环,因为名称仅被指定为 Iron。
using namespace std;
int main()
{
ifstream ClientsFile("clients.txt");
int id;
string name;
double money;
char sep1;
char sep2;
while (ClientsFile >> id >> sep1 >> name >> sep2 >> money)
{
cout << "id: " << id << endl << "name: " << name << endl << "money: " << money << endl << endl;
}
return 0;
}
谢谢。
最佳答案
输入运算符 >>
以空格分隔。相反,您可能想使用 std::getline
读取分号分隔的字段。
类似于
std::string id_string, money_string;
while (std::getline(ClientsFile, id_string, ';') &&
std::getline(ClientsFile, name, ';') &&
std::getline(ClientsFile, money_string))
{
id = std::stoi(id_string);
money = std::stod(money_string);
...
}
关于c++ - 使用 fstream 将文件中的一行读取到不同的变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37106065/