字符串的多组输入格式
1. scanf("%c", &ch)
读取单个字符。
刷题记录:[题] 查找最大元素 #字符输入
逐个字符手动读取,因为题目的要求,要对每个字符逐个操作,所以就输入的时候顺便比较大小了。
在这道题里面
- 每组输入最后会有一个
EOF
表示这组输入结束了。
#include<bits/stdc++.h>
using namespace std;
int main() {
char s[100000];
while(scanf("%c", &s[0]) != EOF) {
int len = 1;
while(scanf("%c", &s[len]) && s[len] != '\n') {
len ++;
}
}
return 0;
}
2. gets(str)
读取char[N]
定义的字符串,不用加结束条件进行判断。
- 能读空格,遇到换行才结束。
#include<bits/stdc++.h>
using namespace std;
char str[101];
int main() {
while(gets(str)) {
}
return 0;
}
从下面例子可以看到,这样读进去的字符串,会在最后面加上
'\0'
#include<bits/stdc++.h>
using namespace std;
char str[101];
int main() {
gets(str);
for(int i = 0;;i ++) {
if(str[i] == '\0') {
printf("遇到'\\0'了,在第%d位这里", i);
break;
}
else
printf("%c", str[i]);
}
return 0;
}
3. getline(cin, s)
读取string
定义的字符串,不用加结束条件进行判断。
- 能读空格,遇到换行才结束。
string s
的长度用strlen(s)
来获取
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
while(getline(cin, s)) {
}
return 0;
}
从下面例子可以看到,这样读进去的字符串,会在最后面加上
'\0'
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin, s);
for(int i = 0;;i ++) {
if(s[i] == '\0') {
printf("遇到'\\0'了,在第%d位这里", i);
break;
}
else
printf("%c", s[i]);
}
return 0;
}