2011-10-15 15 views
1

我編寫了下面的代碼,成功從文件中獲取一行隨機行;但是,我需要能夠修改其中一行,因此我需要能夠逐字符地獲取行字符。 如何更改我的代碼來執行此操作?HW Help:獲取char而不是獲取行C++

回答

2

使用std::istream::get而不是std::getline。只需逐字讀一遍字符串,直到達到\nEOFother errors。我還建議您閱讀完整std::istream reference

祝您的作業順利!

UPDATE:

OK,我不認爲一個例子傷害。這裏是我會做,如果我是你:

#include <string> 
#include <iostream> 
#include <fstream> 
#include <cstdlib> 

using namespace std; 

static std::string 
answer (const string & question) 
{ 
    std::string answer; 
    const string filename = "answerfile.txt"; 
    ifstream file (filename.c_str()); 

    if (!file) 
    { 
     cerr << "Can't open '" << filename << "' file.\n"; 
     exit (1); 
    } 

    for (int i = 0, r = rand() % 5; i <= r; ++i) 
    { 
     answer.clear(); 
     char c; 

     while (file.get (c).good() && c != '\n') 
     { 
      if (c == 'i') c = 'I'; // Replace character? :) 
      answer.append (1, c); 
     } 
    } 

    return answer; 
} 

int 
main() 
{ 
    srand (time (NULL)); 

    string question; 

    cout << "Please enter a question: " << flush; 
    cin >> question; 
    cout << answer (question) << endl; 
} 

...唯一的事情是,我不知道爲什麼你需要通過字符以改一改串字符。你可以修改std :: string對象,這更容易。假設你想用「假設」代替「我認爲」?你可能會更好閱讀更多關於 std::string和使用finderasereplace

更新2:

與最新的代碼會發生什麼事是簡單,就是 - 你打開一個文件,然後你它的內容逐字符直到達到換行符(\n)。因此,無論哪種情況,您最終都會閱讀第一行,然後您的do-while循環將終止。如果你看看我的例子,我做while循環讀取行,直到\n在for循環中。所以這基本上是你應該做的 - 重複你的do-while循環,你可以從那個文件中得到/想要多少行。例如,像這樣的東西會讀你兩行:

for (int i = 1; i <= 2; ++i) 
{ 
    do 
    { 

     answerfile.get (answer); 
     cout << answer << " (from line " << i << ")\n"; 
    } 
    while (answer != '\n'); 
} 
+0

int r,number; \t srand(time(NULL)); \t r = rand()%number +1; \t \t \t char answerchar; \t do {for(int i = 0; i Jessica

+0

@Jessica:你正在使用未初始化的變量'number' ... – 2011-10-15 23:59:41

+0

@VladLazarenko不,r和數字都被初始化爲整數。 – Moses