一. c/c++如何整行读取字符串或字符数组:
https://www.cnblogs.com/AlvinZH/p/6798023.html
二. 整行读取后的分割操作:
例题:hdu 2072(统计单词数)
输入:有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束
输出:输出每行(每组)的单词数目
Sample Input
you are my friend #
Sample Output
4
分析题目:
水题,重点在于输入数据的处理
第一种方法:
使用C语言的库函数strtok来切割字符串。其好处在于,可以指定任意字符作为分隔符来切割单词。
然后用string类型的set集合(相同数据会自动排除)去保存这些数据,然后mylen=a.size();
代码:这种字符数据使用了字符数组
#include<iostream> #include<set> #include<string.h> using namespace std; int main() { char str[1024]; while(gets(str)&&str[0]!='#') { set<string> a; char *s=" "; char *token; token=strtok(str,s); while(token!=NULL) { a.insert(token); token=strtok(NULL,s); } cout<<a.size()<<endl; } }
第二种方法:
程序中使用set、<sstream>(字符串流)中的istringstream以及string。
代码:这种字符数据使用了字符串
#include<iostream> #include<set> #include<cstdio> #include<string.h> #include<sstream> using namespace std; int main() { string s; while(getline(cin,s)&&s!="#") { istringstream sin(s); set<string> words; string s2; while(sin>>s2) words.insert(s2); cout<<words.size()<<endl; } return 0; }