gpt4 book ai didi

c++ - 读取此文件行的最短方法?

转载 作者:太空狗 更新时间:2023-10-29 23:32:45 25 4
gpt4 key购买 nike

我有一个包含如下行的文件:

Alice 60 30 75
Bob 20 250 12

其中名称和整数长度是可变的。将名称放入字符串并将整数放入大小为 3 的数组的最短方法是什么?我做了一个 getline() 然后将第一个字符推到第一个空格到一个字符 vector 中,转移到字符串,然后将下一个字符放到空格中,使用 atoi() 转换然后发送到数组,等等。我觉得有可能是更好的方法?

我尝试了这条建议行:

int main() {
ifstream infile("wheelgame.txt");
string s;
vector<int> a(3);

while (cin >> s >> a[0] >> a[1] >> a[2])
{
cout << "test";
}

}

但我想我是不是误会了?它以这种方式永远运行。

最佳答案

更短的路

std::string s;
std::vector<int> a(3); // or int a[3]; or std::array<int, 3> a;
std::cin >> s >> a[0] >> a[1] >> a[2];

编辑:将 while 循环更改为从文件而不是标准输入(即 cin)读取

while (infile >> s >> a[0] >> a[1] >> a[2]) {
...
}

这个循环不会一直运行下去。

关于c++ - 读取此文件行的最短方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com