迭代器《C++ primer》第三章迭代器问题,有没有更好的终止输入流的方法,while(cin>>word)遇到什么情况终止,求高手指点
读入一段文本到 vector 对象,每个单词存储为 vector 中的一个元素。把 vector 对象中每个单词转化为大写字母。输出 vector 对象中转化后的元素,每八个单词为一行输出。
问题:输入流以123结束,有没有更好的终止输入流的方法,如何引入输入流中断的问题
#include<iostream>
#include <vector>
#include <string>
using namespace std;
using std::vector;
int main(){
vector<string> text;
string word;
while(cin>>word){//为文本添加单词,以123结束,有没有更好的终止输入流的方法
if (word != "123")
{
text.push_back(word);
}
else break;
}
vector<string>::size_type i=0;
for (;i!=text.size();i++)
for(string::size_type j=0;j!=text[i].size();j++){
text[i][j]=toupper(text[i][j]);
}
int index = 0;
for (;index!=text.size();index++)
{
if (index % 8 == 0)
{
cout<<endl;
}
cout<<text[index]<<" ";
}
}
[解决办法]
用回车做结束
你看看这样会不会好一些
#include<iostream>#include <vector>#include <string>using namespace std;using std::vector;int main(){ vector<string> text; string word; while(cin>>word){//为文本添加单词,以123结束,有没有更好的终止输入流的方法 /*if (word != "123") { text.push_back(word); } else break;*/ text.push_back( word ); if( cin.get() == '\n' ) break; } vector<string>::size_type i=0; for (;i!=text.size();i++) for(string::size_type j=0;j!=text[i].size();j++){ text[i][j]=toupper(text[i][j]); } int index = 0; for (;index!=text.size();index++) { if (index % 8 == 0) { cout<<endl; } cout<<text[index]<<" "; }}
[解决办法]
vector<string>::iterator iter; for (;iter!=text.end();iter++) for(string::size_type j=0;j!=(*iter).size();j++){ (*iter)[j]=toupper((*iter)[j]); }
[解决办法]
这个 问题 我初学的时候 也遇到过!
我是自己定义了个头文件,然后使用头文件里的函数 来判断是否为字符 来中止的!
头文件代码如下:
[code=C/C++][/code]#ifndef ISSTRING
#define ISSTRING
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
inline bool isstring(const string &sf)
{
string sd("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM");
bool is=true;
//string::size_type pos=0;
//while(sf.find_first_of(sd,pos)==string::npos)
while(sf.find_first_of(sd)==string::npos)
{
is=false;
break;
}
return is;
}
#endif
使用示例:
string str;
while(cin>>str&&isstring(str));
[解决办法]
#include <conio.h>
(key = cin.getch()) == 0x1b (Esc键结束。)