C++ 从文本文件中读取特定整数

C++ 从文本文件中读取特定整数,c++,file-io,text-files,C++,File Io,Text Files,我有一个包含此信息的文本文件 GO pink colour 60 5 0 pink colour 80 10 0 chocs red colour 100 15 1 red colour 120 15 1 man blue colour 140 20 2 fast place Brown colour 160 20 2 Going in plane Green colour 280 35 5 去 粉红色60 5 0 粉红色80 10 0 巧克力 红色100 15 1 红色1

我有一个包含此信息的文本文件

GO pink colour 60 5 0 pink colour 80 10 0 chocs red colour 100 15 1 red colour 120 15 1 man blue colour 140 20 2 fast place Brown colour 160 20 2 Going in plane Green colour 280 35 5 去 粉红色60 5 0 粉红色80 10 0 巧克力 红色100 15 1 红色120 15 1 男人 蓝色140 20 2 禁地 棕色160 20 2 坐飞机去 绿色280 35 5 我试图只提取每行的第一个整数。没有整数的行我可以跳过。 所以我可以跳过第1行(
Go
) 但是我需要第2行的
60
。 和第3行的
80
。 跳过第4行。等
但是我不知道怎么做。非常感谢您的帮助。谢谢

您可以一次读取一个字符,然后检查该字符是否为数字。如果是,则继续阅读,直到你碰到一个不是数字的字符。然后忽略所有内容,直到角色成为换行符。它可能看起来像:

char buff;
std::fstream fin("file", std::fstream::in);

buff = fin.getchar();

// Read until end of file
while (buff != file.EOF)
{
    // if the char we read is a digit...
    if (isdigit(buff))
    {
        // Continue to read characters if they are an integer (same number)
        while (isdigit(buff))
        {
            // Store buff in some container
        }

        // Ignore until we hit the end of that line
        fin.ignore(256, '\n');      
    }
}
您可以这样做:

#include <iostream>
#include <sstream>
using namespace std;

... ...

string str;
while (getline(file, str)) // read each line
{
    istringstream iss(str);
    int value;
    string temp;
    if (iss >> temp >> temp >> value) // try to read the value
    {
        // you got the value here
    }
}
#包括
#包括
使用名称空间std;
... ...
字符串str;
while(getline(file,str))//读取每一行
{
istringstream iss(str);
int值;
字符串温度;
if(iss>>temp>>temp>>value)//尝试读取该值
{
//你在这里得到了价值
}
}
伪代码:

read in a line, quit at EOF
for each line
    do a **string::find_first_of** for a digit
    if digit not found, go to read the next line
    do a **std::stoi** to convert to integer
    process the integer

到目前为止,我在for循环中逐行读取文本文件。我试过了。但是整数不是在每一行的同一位置,它只对第一行有效。