2016-02-27 112 views
1

screenshot 嗨,大家好我想讀取一個文本文件,在一行中有3個雙打,然後將這三個值保存到我的變量(每變量1個變量)。C++從文本文件讀取雙打

到目前爲止,我的代碼看起來像這樣:

cout<<"ready to read file...:"; 
ifstream theFile("pose.txt"); 
double first,second,third; 
while(theFile >> first >> second >> third){ 
    cout<<"In while loop and got following values: "; 
    cout<< first<<endl<< second <<endl<< third; 
} 

我的輸入文件看起來像這樣打開時:

1.5 2.4 3.3 

然而,即使第一COUT運行,它告訴我,程序準備好讀取文件,它不會進入while循環。

我試過使用其他讀取文件的方法,這也是無效的。

歡迎任何幫助, 謝謝。

+2

發佈您的輸入文件... –

+1

您是否試圖在調試器中逐行執行代碼? –

+0

我也發佈了我的輸入文件,是的,我試過調試,但我不確定它看起來好像跳過while循環的開始。 –

回答

0

我在StackOverflow的另一個問題上找到了答案。 這是鏈接到了答案: https://stackoverflow.com/a/23448835/4117002

基本上我不得不在Xcode指定文本文件的路徑,儘管我已經創造了它在該項目。

感謝無論如何每個人的幫助!

0

我不從截圖中認識你的IDE,但如果它像其他的IDE, 你的程序將不會被默認包含 源文件main.cpp的目錄中運行,數據文件example.txt。 它將在項目 設置中配置的目錄中運行,可能是創建可執行文件的目錄。

所以讓我們假裝在Products/Debug和 在那裏運行創建(調試版本)可執行文件。在這種情況下:

std::ifstream theFile("example.txt"); 

會失敗,因爲沒有在Products/Debug稱爲example.txt文件。 您需要打開theFile與相對路徑:

std::ifstream theFile("../../InputFileExample/example.txt"); 

或者指定的絕對路徑。

0

假設你熟悉CPP:

  1. 緩衝區每一行ifstream數據爲std::string。例如:

    std::getline(std::ifstream , std::string) 
    
  2. 緩衝區的std::stringstd::istringstream。例如:

    std::istringstream (std::string) 
    
  3. 拆分std::istringstream到你所需要的雙重價值。例如:

    istringstream iss 
    

iss >> first >> second >> third 

祝您好運!