如何输入包含少于1000个单词的带有空格和标点符号的文本
How to input text containing less than 1000 words with spaces and punctuations?
我可以使用以下代码输入字符串:
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
您可以指定第三个参数来限制读取的字符数。
相关文章:
- 2D数组来自文本输入,中间有空格
- 从文本文件中读取所有内容,直至空格
- 使用空格分隔符从文本文件将对象读入数组
- 从文本文件中读取数据并删除所有换行符空格,并在 C++ 控制台中显示
- 崇高文本 3 - 在终端中编译并运行 C++ 程序(路径包含空格)
- 非空格分隔的文本文件到 2D 矢量
- 从文件中读取带有空格和数字数据的文本
- 通过删除C 中的评论,额外的空格和空白行,从文本文件中换成元素
- 将文本写入文件,包括空格
- 使用 + 和空格将字符串与文本串联
- 文本文件解析C++|用空格分隔
- 打开文本文件并读取一个带有空格的字符串,然后将两个独立的int放入一个结构中
- 知道文本文件中的列数,用空格或制表符分隔
- 有效地检查文本文件是否完全由空格c++组成
- C++ 从空格分隔的文本文件中填充字符串向量
- 将具有多个空格的字符串添加到文本文件
- 如何从文本文件 c++ 中读取具有一定长度空格的输入字符串
- 以C++打印出文本文件中的空格
- 读取空格将数字从文本文件分隔到整数数组 (C++)
- 将包含空格的文件中的文本存储为字符串