[英]Cannot read integers from a txt file containing 2 columns (C++)
我必須編寫一條代碼,提示用戶輸入文件名(包含2列整數)。 然后程序讀取該文件,打印出設置的數字。
我的txt文件如下所示(數字之間用空格分隔):
2 3
5 6
7 8
8 9
5 7
我以為會很容易,但現在我堅持了下來。 當我運行程序時,此行出現
“文件中沒有數字。”
我將數字設置為“ int”,為什么編譯器無法讀取該數字? 但是當我將類型更改為“字符串”時,數字的確出現了O_O,因為我后來還需要計算這些數字的平均值,所以我不能使用字符串。
這是我的代碼,感謝您的幫助TT___TT
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream in_file;
string filename;
int number;
int number1;
cout << "In order to process, please enter the file name: ";
cin >> filename;
in_file.open(filename.c_str());
if (!in_file.is_open())
{
cout << "Cannot open file" << endl;
}
else
{
in_file >> number;
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
}
system("pause");
return 0;
}
您的邏輯錯誤:
in_file >> number; // Assigns 2 from first line to number
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1) // Assigns 3 to number from first line
// and assigns 5 to number1 from second line
{
cout << number << " " << number1;
}
您只需要使用:
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
如果必須打印“文件中沒有數字”。 在輸出中,可以使用:
bool gotSomeNumbers = false;
while (in_file >> number >> number1)
{
cout << number << " " << number1;
gotSomeNumbers = true;
}
if (!gotSomeNumbers)
{
cout << "There're no number in the file." << endl;
}
您用來查找文件是否為空的方法不正確,方法如下:::一旦執行此行
in_file >> number;
編譯器會將第一行視為一個整體,即在給定情況下number =“ 2 3”。 現在這不是標准數字,因為2到3之間的空格和
in_file.fail()
將返回true。正確的方法是使用“ eof”函數,如下所示:(我還添加了1-2行來計算這些數字的平均值)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.