(C )在读取文件时,如何将GetLine()与整数一起使用



我正在尝试创建一些代码以打开文件,读取内容并通过使用getline()检查一个整数是否相等。问题在于它似乎仅适用于字符串,而不是与整数一样。你能帮我吗?

fstream ficheroEntrada;
string frase;
int dni, dnitxt;
int i=0;
int time;
cout << "Introduce tu DNI: ";
cin >> dni;
ficheroEntrada.open ("Datos.txt",ios::in);
if (ficheroEntrada.is_open()) {
    while (! ficheroEntrada.eof() ) {
        getline (ficheroEntrada, dnitxt);
        if (dnitxt == dni){
            getline (ficheroEntrada, frase);
            cout << dni << " " << frase << endl;        
        }else{
            getline (ficheroEntrada, dnitxt);
        }   
    }
    ficheroEntrada.close();
}

getline()成员函数用于提取字符串输入。因此,如果您以字符串的形式输入数据,然后使用" stoi"(代表字符串到整数),那就更好了,仅从字符串数据中提取整数值。您可以单独检查如何使用" Stoi"。

getline一次不读取整数,一次是字符串,整行。

如果我理解正确,则在文件Datos.txt中搜索int dni。文件的格式是什么?

假设它看起来像这样:

4
the phrase coressponding to 4
15
the phrase coressponding to 15
...

您可以使用stoi将您阅读的内容转换为整数:

string dni_buffer;
int found_dni
if (ficheroEntrada.is_open()) {
    while (! ficheroEntrada.eof() ) {
        getline (ficheroEntrada, dni_buffer);
        found_dni = stoi(dni_buffer);
        if (found == dni){
            getline (ficheroEntrada, frase);
            cout << dni << " " << frase << endl;        
        }else{
            // discard the text line with the wrong dni
            // we can use frase as it will be overwritten anyways
            getline (ficheroEntrada, frase);
        }   
    }
    ficheroEntrada.close();
}

未测试。

C 有两种类型的getline
其中之一是std::string中的非会员功能。此版本从流到std::string object getline提取。喜欢:

std::string line;
std::getline( input_stream, line );

另一个是 input-stream 的成员函数,例如std::ifstream,此版本 extfracts 从流到 arnay array 像:

char array[ 50 ];
input_stream( array, 50 );

注意
这两个版本提取来自流的字符不是真正的整数类型!


有了答案,您应该知道文件中有哪种类型的数据。这样的文件: I have only 3 $dollars!;当您尝试阅读该内容时,通过使用std::getlineinput_stream.getline,您不能提取3如Integer Type!。而不是getline,您可以使用operator >>一对一地提取单个数据;喜欢:
input_stream >> word_1 >> word_2 >> word_3 >> int_1 >> word_4;

现在int_1具有:3


实例

std::ifstream input_stream( "file", std::ifstream::in );
int number_1;
int number_2;
while( input_stream >> number_1 >> number_2 ){
    std::cout << number_1 << " == " << number_2 << " : " << ( number_1 == number_2 ) << 'n';
}
input_stream.close();

输出:

10 == 11 : 0
11 == 11 : 1
12 == 11 : 0

最新更新