2017-03-03 256 views
0

我想创建一些代码来打开一个文件,阅读内容,并检查是否有几个整数是相等的使用getline()。问题是它似乎只能用字符串工作,而不是用整数来完成。你可以帮帮我吗?(C++)如何在读取文件时使用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(); 
} 
+1

使用'ficheroEntrada >> dnitxt;'代替。 –

+0

做了任何答案有助于您的问题?关心提供更多的反馈? –

回答

1

getline()成员函数用于提取字符串输入。因此,如果以字符串形式输入数据,然后使用“stoi”(表示字符串到整数)从字符串数据中仅提取整数值,会更好。 你可以单独检查如何使用“stoi”。

0

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(); 
} 

这不是测试。

1

C++有两种类型getline
其中之一是std::string中的非成员函数。该版本从流中将提取为std::string objectgetline。像:

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

另一种是一个输入流std::ifstream的成员函数和该版本提取从流成阵列字符getline的像:

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

备注
两个版本摘录字符流不是一个真正的整数类型!


为了回答您的问题,您应该知道您的文件中包含哪些类型的数据。像这样的文件:I have only 3 $dollars!;当你尝试读取,通过使用std::getlineinput_stream.getline不能提取3在整数类型!!您可以使用operator >>来逐个提取单个数据,而不是使用getline;如:
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 
相关问题