我正在从标准输入流中获取输入,例如,
1 2 3 4 5
或者1
2
3
4
5
我正在使用:
std::string in;
std::getline(std::cin, in);
但是那只是获取到换行符之前的内容,对吗?我该如何使用仅限 iosteam、string 和 cstdlib 来获取用户输入,无论它们是用换行符还是空格分隔?
直接使用:
your_type x;
while (std::cin >> x)
{
// use x
}
operator>>
默认会跳过空格。你可以链接多个变量以一次读取它们:
if (std::cin >> my_string >> my_number)
// use them both
getline()
函数读取一整行内容,即使该行为空或包含数十个以空格分隔的元素,它也会将其全部读入返回。如果你提供可选的备用定界符(如:getline(std::cin, my_string, ' ')
),它仍然无法满足你想要的需求,例如制表符会被读入到my_string
中。
也许现在不需要,但你可能在不久的将来会遇到一个相当常见的需求,即读取单独由换行符分隔的一行,然后将其拆分成各个组成部分...
std::string line;
while (std::getline(std::cin, line))
{
std::istringstream iss(line);
first_type first_on_line;
second_type second_on_line;
third_type third_on_line;
if (iss >> first_on_line >> second_on_line >> third_on_line)
...
}
if (std::cin >> my_string >> my_number)
处理了数字可能出现在水平和/或垂直方向的情况。 - lifebalance使用'q'
作为getline
的可选参数。
#include <iostream>
#include <sstream>
int main() {
std::string numbers_str;
getline( std::cin, numbers_str, 'q' );
int number;
for ( std::istringstream numbers_iss( numbers_str );
numbers_iss >> number; ) {
std::cout << number << ' ';
}
}
std::getline( stream, where to?, delimiter ie
std::string in;
std::getline(std::cin, in, ' '); //will split on space
或者你可以将文本读入一行,然后根据任何你希望的分隔符进行标记化。
int count = 5;
int list[count]; // array of known length
cout << "enter the sequence of " << count << " numbers space separated: ";
// user inputs values space separated in one line. Inputs more than the count are discarded.
for (int i=0; i<count; i++) {
cin >> list[i];
}
int main()
{
int m;
while(cin>>m)
{
}
}
如果输入是以空格分隔或换行符分隔的,则会从标准输入读取。
#include <iostream>
using namespace std;
string getWord(istream& in)
{
int c;
string word;
// TODO: remove whitespace from begining of stream ?
while( !in.eof() )
{
c = in.get();
if( c == ' ' || c == '\t' || c == '\n' ) break;
word += c;
}
return word;
}
int main()
{
string word;
do {
word = getWord(cin);
cout << "[" << word << "]";
} while( word != "#");
return 0;
}
只需使用:
string line;
getline(cin >> ws, line);
这里有详细描述:https://www.geeksforgeeks.org/problem-with-getline-after-cin/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> i;
int n;
while (cin >> n) {
i.push_back(n);
if (cin.peek() == '\n')
break;
}
cout << i.size() << '\n';
return 0;
}
getline
应该如何知道何时返回? - ildjarn