我編寫了下面的代碼,成功從文件中獲取一行隨機行;但是,我需要能夠修改其中一行,因此我需要能夠逐字符地獲取行字符。 如何更改我的代碼來執行此操作?HW Help:獲取char而不是獲取行C++
1
A
回答
2
使用std::istream::get
而不是std::getline
。只需逐字讀一遍字符串,直到達到\n
,EOF或other 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
和使用find
,erase
,replace
等
更新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');
}
相關問題
- 1. CSC help - C#獲取直接輸出
- 2. mysql_fetch_row獲取列而不是行
- 3. JQgrid - 獲取行號而不是ID
- 4. 獲取NaN而不是值
- 5. 獲取,而不是Microsoft.SharePoint.Client.FieldUserValue
- 6. 從char獲取KeyCode?
- 7. 從`ByteString`獲取`Char`
- 8. 獲取字節[]從在C++中的char *
- 9. 從Unicode值獲取char - 目標C
- 10. C++如何獲取sizeof(枚舉)== sizeof(char)?
- 11. 即時獲取{{}}而不是獲取C#中的文本框的值
- 12. 獲取值的密鑰而不是獲取密鑰值?
- 13. iphone,獲取對象數而不執行獲取?
- 14. C++獲取多行
- 15. C#獲取行號
- 16. 如何獲取Spotlight For Help菜單項
- 17. 如何通過indexPath.row獲取uitableViewCell或者僅獲取行號而不是indexpath?
- 18. 重複行而獲取
- 19. PHP獲取char的值?
- 20. 從maskedTextBox獲取byte [](或char [])
- 21. 從CString獲取char字符
- 22. 在java中獲取char值
- 23. 獲取容器VC而不是視圖
- 24. 獲取鏈接,而不是在ASP.NET MVC
- 25. 獲取TruncatedSVD.transform()返回float16而不是float64
- 26. 獲取符號而不是INT
- 27. 獲取EXC_BAD_INSTRUCTION而不是失敗
- 28. 從Mysql獲取數據,而不是XML?
- 29. Xamarin__HttpClient__HttpResponseMessage-Content ---獲取HTML而不是JSON
- 30. 從MySQL查詢獲取,而不是表
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
@Jessica:你正在使用未初始化的變量'number' ... – 2011-10-15 23:59:41
@VladLazarenko不,r和數字都被初始化爲整數。 – Moses