我有一个由以下行组成的文件:
Alice 60 30 75
Bob 20 250 12
名称和整数长度是可变的。将名称放入字符串并将整数放入大小为3的数组中的最短方法是什么?我做了一个getline(),然后将第一个char推送到第一个空格成为char矢量,转移到字符串,然后将下一个char转换为空格,使用atoi()转换然后发送到数组等等。我觉得在那里& #39;可能是一个更好的方式?
我尝试了以下建议:
int main() {
ifstream infile("wheelgame.txt");
string s;
vector<int> a(3);
while (cin >> s >> a[0] >> a[1] >> a[2])
{
cout << "test";
}
}
但我认为我是误会?它以这种方式永远运行。
答案 0 :(得分:10)
更短的方式
AutoDetectSpectrometer()
编辑:更改while循环以从文件而不是stdin(即cin)读取
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];
此循环不会永远运行。
答案 1 :(得分:2)
如果您的字符串是char数组,并且您不想使用STL:
char str[MAX];
int a[3];
fscanf(file, "%s %d %d %d", str, &a[0], &a[1], &a[2]);