getline c++ 的问题
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() 不包括行 return:
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”,换行符 return)。
您需要添加自己的换行符:
for (int i=0; i<=Number; i++){
cout<<Character;
if (i != Number) {
cout << '*';
}
}
cout << "\n";
想做一些花哨的格式化。我有几行要相互交互。获取前两行。打印出第二行中的字符乘以第一行中的整数。用星号字符将它们全部分开。打印最后一个字符后没有星号。移动到下一个整数和字符。将它们打印在单独的行上。对整个列表执行此操作。我遇到的问题是将它们打印在不同的行上。示例:
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() 不包括行 return:
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”,换行符 return)。
您需要添加自己的换行符:
for (int i=0; i<=Number; i++){
cout<<Character;
if (i != Number) {
cout << '*';
}
}
cout << "\n";