我可以使用以下代码输入字符串:
string str;
getline(cin, str);
但我想知道如何对可以作为输入的单词数量设置上限。
仅使用getline
甚至read
都无法满足您的要求。如果您想限制字数,可以使用简单的for
循环和stream-in运算符。
#include <vector>
#include <string>
int main()
{
std::string word;
std::vector<std::string> words;
for (size_t count = 0; count < 1000 && std::cin >> word; ++count)
words.push_back(word);
}
这将读取多达1000个单词,并将它们填充到一个向量中。
getline()
读取字符,不知道单词是什么。单词的定义可能会随着上下文和语言的变化而变化。您需要一次读取一个流中的一个字符,提取符合您对单词定义的单词,并在达到限制时停止。
您可以一次读取一个字符,也可以只处理字符串中的1000个字符。
您可以设置std::string的限制并使用它。
以下内容将只读count
,矢量中没有用空格分隔的单词,丢弃其他。
在这里,标点符号也被理解为"单词"由空格分隔,您需要将它们从向量中删除。
std::vector<std::string> v;
int count=1000;
std::copy_if(std::istream_iterator<std::string>(std::cin),
// can use a ifstream here to read from file
std::istream_iterator<std::string>(),
std::back_inserter(v),
[&](const std::string & s){return --count >= 0;}
);
希望这个程序能帮助你。此代码处理单行中多个单词的输入以及
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int LIMIT = 5;
int counter = 0;
string line;
string words[LIMIT];
bool flag = false;
char* word;
do
{
cout<<"enter a word or a line";
getline(cin,line);
word = strtok(const_cast<char*>(line.c_str())," ");
while(word)
{
if(LIMIT == counter)
{
cout<<"Limit reached";
flag = true;
break;
}
words[counter] = word;
word = strtok(NULL," ");
counter++;
}
if(flag)
{
break;
}
}while(counter>0);
getchar();
}
到目前为止,这个程序只能接受5个单词并将其放入字符串数组中。
使用以下函数:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961%28v=vs.85%29.aspx
您可以指定第三个参数来限制读取的字符数。