在我嘗試在C++中創建自動數獨求解器時,我需要的第一步是從文件中讀取9x9網格。目前我只是試圖簡單地讀取數據,並將其顯示爲輸出,但輸出不正確。我的代碼如下:從文件中讀取整數返回錯誤的輸出(ifstream)
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// Initialize string for the lines to be read in
string line;
// Create the object to read the file "data.txt"
ifstream sudokuData("data.txt");
// Check if file opened properly
if (!sudokuData.good()) {
cout << "Couldn't open the file.\n";
}
// Read only if file exists
if (sudokuData.is_open()) {
cout << "Starting to read from file... \n";
// Read as long as there are lines in the file
while (getline(sudokuData,line)) {
cout << line << '<\n';
}
// Close file once done reading
sudokuData.close();
} else {
// If file cannot be read, inform the user
cout << "Unable to open file";
}
return 0;
}
從我所能找到的,這是正確的。數據文件包含每行中從1到9的數字,用空格分隔。一個例子行將是:
1 2 3 4 5 6 7 8 9
但是當我運行的代碼,我得到以下輸出:
Starting to read from file
153709 1 2 3 4 5 6 7 815370
RUN SUCCESSFUL (total time: 38ms)
到底什麼我做錯了什麼?
我使用NetBeans 8.0 IDE作爲,如果沒有任何用處的......
你在哪裏getline()方法? –
@EduardoDennis http://www.cplusplus.com/reference/string/string/getline/ – dari
仔細檢查文件中是否存在垃圾,不可打印,utf-8編碼或Unicode字符。 –