我是c ++的新手,并尝试将字符作为输入,直到用户输入换行符。我的示例代码如下:
#include<iostream>
using namespace std;
main()
{
char c;
while(1)
{
cin>>c;
if(c=='\n')
{
cout<<"Newline";
break;
}
}
}
问题是按下键盘输入键后循环没有断开。代码有什么问题吗?
默认情况下,使用重载的>>
运算符的所有输入都会跳过任何类型的空白区域。如果要读取空白区域,请使用std::noskipws
操纵器(或设置相应的流标志)。
这是我认为适合你的东西:
#include<iostream>
#include<iomanip>
bool treat_line(std::istream& is)
{
char c;
while(is)
{
is >> std::noskipws >> c;
if(c == '\n')
{
std::cout << "Newline\n";
break;
}
else
std::cout << c;
}
return bool(is); // convert "OK" state of stream to boolean
}
int main()
{
while(treat_line(std::cin))
;
std::cout << "done\n";
}
但是,您似乎想要做的是将数据视为“一次一行”。已有一个功能:
#include <iostream>
#include <string>
int main()
{
while(std::cin)
{
std::string line;
std::getline(std::cin, line);
if (!line.empty())
{
std::cout << "handing line: " << line << std::endl;
}
}
std::cout << "done\n";
}
可以使用getline选项。 getline是c ++中提供的标准库函数,用于从输入流中读取字符串或行。
语法:istream&getline(istream&is,string&str);
is - 它是istream类的对象。
str - 存储输入的目标变量。
示例程序:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str;
cout << "Please enter your name: \n";
getline (cin, str);
cout << "Hello, " << str ;
return 0;
}
获得多行输入。例如,以下程序可用于获得四行用户输入。
// A simple C++ program to show working of getline
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str;
int t = 4;
while (t--)
{
// Read a line from standard input in str
getline(cin, str);
cout << str << " : newline" << endl;
}
return 0;
}