我尝试修改此代码以打印
no solution如果没有用户输入。也就是说,如果我运行该程序并简单地按enter键,它应该会打印no solution。我添加了用于执行此操作的代码,以检查字符串长度是否为0,然后打印,但它不起作用
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i, j, ctr;
fgets(str1, sizeof str1, stdin);
j = 0; ctr = 0;
if (strlen(str1) == 0) {
printf_s("no solution");
}
else
for (i = 0; i <= (strlen(str1)); i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if (str1[i] == ' ' || str1[i] == '\0')
{
newString[ctr][j] = '\0';
ctr++; //for next word
j = 0; //for next word, init index to 0
}
else if (str1[i] == '.' || str1[i] == ',')
{
newString[ctr][j] = '\0';
ctr--; //for next word
j = - 1;
}
else
{
newString[ctr][j] = str1[i];
j++;
}
}
printf("\n\n");
for (i = 0; i < ctr; i++)
printf(" %s\n", newString[i]);
return 0;
}发布于 2020-04-16 14:08:45
fgets()将在字符串中添加新行(有关详细信息,请参阅此link ),这意味着当您只需按enter键时,您的字符串长度(因为字符串包含\n)为1,您应该说:
if (strlen(str1) == 1) {
printf_s("no solution");
// it's better to add a return 0; here if you don't want to continue the program
}或者使用下面的代码:
if (!strcmp(str1,"\n")) {
printf_s("no solution");
}https://stackoverflow.com/questions/61243674
复制相似问题