我想在每一行的每个单词上打字。看起来像putc不工作以及为什么我不能在c编程语言中使用putchar?
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main() {
char s[50];
int i, len;
printf("\enter string : ");
gets(s);
len = strlen(s);
i = 0;
while (i<len) {
while (s[i] == ' ' && i<len)
i++;
while (s[i] != ' ' && i<len)
putc(s[i++], stdout);
putc('\n', stdout);
}
getch();
}
答案 0 :(得分:0)
您的代码没有大量错误,除了:
conio.h
和getch
; while
语句中条件的错误顺序,可能会导致未定义的行为。因此,此代码似乎可以满足您的需求:
#include <stdio.h>
#include <string.h>
int main (void) {
char s[50];
int i, len;
printf("enter string : ");
gets(s);
len = strlen(s);
i = 0;
while (i<len) {
while (i < len && s[i] == ' ')
i++;
while (i < len && s[i] != ' ')
putc(s[i++], stdout);
putc('\n', stdout);
}
return 0;
}
然而,它不是那么干净,专业编码人员倾向于选择更多的模块化和有价值的评论,这与以下内容类似。首先,一些跳过空格和回显单词的一般函数:
#include <stdio.h>
#include <string.h>
static char *skipSpaces (char *pStr) {
// Just throw away spaces, returning address of first non-space.
while (*pStr == ' ')
pStr++;
return pStr;
}
static char *echoWord (char *pStr) {
// If at end of string, say so.
if (*pStr == '\0')
return NULL;
// Echo the word itself.
while ((*pStr != '\0') && (*pStr != ' '))
putchar (*pStr++);
// Then skip to start of next word (or end of string).
pStr = skipSpaces (pStr);
// Return new pointer.
return pStr;
}
然后,完成后,主程序变得更容易理解:
int main (void) {
// Get string from user in a more safe manner.
char str[50];
printf("Enter string: ");
fgets (str, sizeof (str), stdin);
// Remove newline if there.
size_t len = strlen (str);
if ((len > 0) && (str[len-1] == '\n'))
str[len-1] = '\0';
// Start with first real character.
char *pStr = skipSpaces (str);
// Process words and space groups (adding newline) until at end of string.
while ((pStr = echoWord (pStr)) != NULL)
putchar ('\n');
return 0;
}