c - putc 在单独的行 C 中将字符串打印到单词

标签 c

我想将字符串打印到每行中的每个单词。看起来 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();
}

最佳答案

您的代码没有任何严重错误,除了:

  • 使用 conio.hgetch 等非标准功能;
  • 使用不安全函数(这在类作业中往往不那么重要);
  • 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;
}

然而,它并不是那么干净,专业的编码员会倾向于选择更多的模块化和有值(value)的评论,如下所示。首先,一些用于跳过空格和回显单词的通用函数:

#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;
}

关于c - putc 在单独的行 C 中将字符串打印到单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154523/

相关文章:

c - 在单独的行上打印 10 范围内的素数

c - 如何使用 pthread 并发操作数据?

c - 宏作为宏参数扩展不起作用

c - C 方言会影响 gcc 中的优化吗?

c - 为什么 'man 2 open'说有两种open呢?

c - block 设备驱动程序 - 了解接收到的 ioctl

二叉树的缓存位置

使用阶乘函数和余弦函数通过麦克劳林级数近似计算 cos(x)

python - 三角函数 sin 返回负值

c - 我不明白以下 C 语言代码如何将输出输出为 22