#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char s[1001];
char str[1001][1001];
int j=0;
while(scanf("%s",s)==1)
{
for (int i = 0; i < strlen(s); i++)
{
if(islower(s[i]))
s[i]=toupper(s[i]);
else if(isupper(s[i]))
s[i]=tolower(s[i]);
}
strcpy(str[j],s);
j++;
}
for (int x = j-1; x>=0; x--)
{
printf("%s ",str[x]);
}
return 0;
}
对于这个,我需要按两次ctrl+z并回车才能得到答案; 但对于下面的,我只需要输入即可获得预期的答案。
#include <stdio.h>
#include <string.h>
int main() {
char s[100];
int flag = 1; // 使用 1 表示第一个单词
while (scanf("%s", s) == 1) {
if (flag) {
flag = 0;
printf("%lu", strlen(s));
} else {
printf(",%lu", strlen(s));
}
}
return 0;
}
我不知道什么时候可以使用这种输入方式。而且当涉及到文字问题时,我认为它比fgets容易,所以我不想放弃它。
%s
丢弃前导空格并扫描非空格。它无法检测换行符。.
来表示输入结束。使用 strchr
检查是否有 .
。-end-
。使用 strcmp
检查字符串。当比较完全匹配时,strcmp
返回 0
。#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SIZE 50
#define FS(x) SFS(x)
#define SFS(x) #x
void swapcase ( char *input) {
char *check = input;
while ( *check) { // not the terminating zero
if ( isupper ( *check)) {
*check = tolower ( *check);
}
else {
*check = toupper ( *check);
}
++check;
}
}
int main ( void) {
char word[SIZE + 1] = ""; //+1 for terminating zero
char inputs[SIZE][SIZE + 1] = { ""};
int count = 0;
printf ( "enter words (end with a .)\n");
while ( 1 == scanf ( "%"FS(SIZE)"s", word)) { // scan up to SIZE characters
swapcase ( word);
strcpy ( inputs[count], word);
++count;
if ( count >= SIZE || strchr ( word, '.')) {
break;
}
}
for ( int each = 0; each < count; ++each) {
printf ( "%s ", inputs[each]);
}
printf ( "\n");
}