读取该文件行的最短方法

Shortest way to read this file line?

本文关键字:方法 文件 读取      更新时间:2023-10-16

我有一个由如下行组成的文件:

Alice 60 30 75
Bob 20 250 12

其中名称和整数长度是可变的。把名字放进字符串,把整数放进大小为3的数组,最短的方法是什么?我做了一个getline(),然后把第一个字符推到第一个空格,变成一个字符向量,转移到字符串,然后把下一个字符变成空间,使用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];

EDIT:将while循环改为从file中读取而不是从stdin(即cin)

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

这个循环不会永远运行

如果您的字符串是字符数组,并且您不想使用STL:

char str[MAX];
int a[3];
fscanf(file, "%s %d %d %d", str, &a[0], &a[1], &a[2]);