[英]Having reading numbers from a *.txt file in C++ using fstream
我有一個* .txt文件,其中包含整數,每行一個。 所以文件看起來像
103123
324
4235345
23423
235346
2343455
234
2
2432
我試圖逐行從文件中讀取這些值,以便可以將它們放在數組中。 以下是我為實現該目的而編寫的一些代碼
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int nArray[1000];
int i = 0;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream file("C:\Users\Chinmay\Documents\Array.txt");
//fstream file("C:\Users\Chinmay\Documents\Array.txt", ios_base::out );
//fstream file();
//file.open("C:\Users\Chinmay\Documents\Array.txt", ios_base::out );
bool b = file.is_open();
//file.seekg (0, ios::beg);
int i = file.tellg();
while(!file.eof())
{
//string str;
//getline(file, str);
//nArray[i++] = atoi(str.c_str());
char str[7] = {};
file.getline(str,7);
nArray[i++] = atoi(str);
}
file.close();
return 0;
}
當bool'b'返回true時,文件打開。 但是while循環一次運行就退出了。 並且數組為空。 我在網上查找並嘗試了其他操作,例如此處給出的代碼
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int nArray[100000];
int i = 0;
int _tmain(int argc, _TCHAR* argv[])
{
ifstream in("C:\Users\Chinmay\Documents\Array.txt");
bool b = in.is_open();
if(!in) {
cout << "Cannot open input file.\n";
return 1;
}
char str[255];
while(in) {
in.getline(str, 255); // delim defaults to '\n'
if(in) cout << str << endl;
}
in.close();
return 0;
}
這也會立即返回。 該文件打開,但沒有數據被讀取。 該文件不為空,並且其中包含數據。 有人可以解釋我要去哪里錯嗎? 我正在使用Visual Studio 2011 Beta。
這沒有做您認為正在做的事情:
ifstream file("C:\Users\Chinmay\Documents\Array.txt");
使用正斜杠(即使在Windows上也是如此)並檢查文件打開是否成功:
std::ifstream ifs("C:/Users/Chinmay/Documents/Array.txt");
if (!ifs)
{
// Failed to open file. Handle this here.
}
我認為第二個版本沒有什么錯。
但是,在第一個版本中,您正在調用file.getline(str,7);
該行有時包含一個7位數字。 讀取該內容,直到達到定界符(默認為'\\n'
)為止,或者直到讀取了6個字符為止,在這種情況下,將設置failbit
。
因為您只在while
循環中測試eof
,所以它不會退出。
如果在getline
調用中將7更改為8,並在上一行將char
數組聲明更改為8,則它應該可以工作。
話雖如此,@ Niklas B關於使用int tmp; file >> tmp;
的建議int tmp; file >> tmp;
int tmp; file >> tmp;
並將其存儲在vector
可能是最簡單的解決方案。
這是一段不錯的代碼http://www.java2s.com/Code/Cpp/File/readingatextfile.htm
如果這對您的文件有效,則只需添加您的作業
nArray [i ++] = atoi(line); 結束后
如果它仍然有效..然后注釋掉cout ..最好將其留在注釋中,因為它可能會告訴您的老師您的過程。 有些教授只想看成品,這取決於您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.