[英]Issues with getline c++
想做一些花哨的格式化。 我有幾行想要相互交互。 獲取前兩行。 打印出第二行中的字符乘以第一行中的整數。 用星號字符將它們全部分開。 打印最后一個字符后沒有星號。 移至下一個整數和字符。 在單獨的行上打印它們。 對整個列表執行此操作。 我遇到的問題是將它們打印在不同的行上。 例子:
5
!
2
?
3
#
期望的輸出:
!*!*!*!*!
?*?
#*#*#
我的輸出:
!*!*!*!*!*?*?*#*#*#*
一段代碼。 我正在從一個單獨的文本文件中讀取有關字符和數字的數據。 所以我正在使用 getline 函數。
這是一段代碼:
ifstream File;
File.open("NumbersAndCharacters.txt")
string Number;
string Character;
while(!File.eof(){
getline(File, Number);
getline(File, Character);
//a few lines of stringstream action
for (int i=0; i<=Number; i++){
cout<<Character<<"*";}//end for. I think this is where
//the problem is.
}//end while
File.close();
return 0;
錯誤在哪里? 是循環嗎? 還是我不明白 getline ?
它應該在每個字符乘法完成后打印“endl”或“\\n”。
幾天前我問過這個問題。 它不包括我的代碼。 它被擱置了。 我在 24 小時前編輯了問題並將其標記為版主審核。 版主或擱置它的人沒有回應,所以我重新提問。
如果讀取的字符是其行的最后一個,只需輸入“endl”而不是“*”,因為 getLine() 不包括行返回:
while(!File.eof(){
getline(File, Number);
getline(File, Character);
//a few lines of stringstream action
for (int i=0; i<=Number; i++){
cout<<Character;
if (i == Number)
cout<<endl;
else
cout<<"*";
}
}//end while
getline
不會在文件行尾的換行符中讀取。 您也不要在任何地方添加換行符。 如果您感到困惑,換行符是字符'\\n'
並表示換行符(在 Windows 上通常是“\\n\\r”,換行符回車)。
您需要添加自己的換行符:
for (int i=0; i<=Number; i++){
cout<<Character;
if (i != Number) {
cout << '*';
}
}
cout << "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.