c - 标记字符串

标签 c arrays parsing

我正在编写一个 C 程序来解析字符串并通过将字符串字符分解为由空格分隔的单词来对其进行标记化。我的问题是当我运行当前程序时:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char input[20];

printf("Please enter your word:\n");

scanf("%c", &input);

printf("%c", input[1]);
return 0;

}

如果我要输入单词“This”,我希望在运行程序时返回“h”,但我却得到一个向下的箭头。但是,当输入设置为打印出 input[0] 时,我得到一个“T”。

编辑:我修改了我的代码,现在它打印出我将在下面显示的整个字符串

int main()
{
char input[20];
printf("Please enter your words:\n");
scanf("%s", input);

printf("%s", input);
return 0;

}

我的目标是能够将该字符串分解为我可以搜索以找到空格的字符,从而能够隔离这些单词,例如,如果我的输入是“This is bad”,我希望代码能够打印出 这个

不好

编辑: 我修改了我的代码以适应这些答案之一,但我现在遇到的问题是它无法编译

int main()
{
char input[20];
printf("Please enter your words:\n");
size_t offset = 0;
do
{
scanf("%c", input + offset);
offset++;
}
while(offset < sizeof(input) && input[offset - 1] != '\n');

}


printf("%c", input[]);
return 0;

最佳答案

问题:

1) scanf("%c", input);只设置数组的第一个元素 input .

2) printf("%c", input[1]);打印数组的第二个元素 input ,其中包含未初始化的数据。


解决方法:
小型状态机。字符串大小没有限制,例如 20。

#include <ctype.h>
#include <stdio.h>

int main() {
  int ch = fgetc(stdin);
  while (ch != EOF) {
    while (isspace(ch)) {

      // If only 1 line of input allowed, then add
      if (ch == '\n') return 0;;

      ch = fgetc(stdin);
    }
    if (ch != EOF) {
      do {
        fputc(ch, stdout);
        ch = fgetc(stdin);
      } while (ch != EOF && !isspace(ch));
      fputc('\n', stdout);
    }
  }
  return 0;
}

关于c - 标记字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21739118/

相关文章:

C:在每一位都很重要的地方存储变量的最有效方法

c++ - 生成混淆代码的 C/C++ 编译器

c - 浏览结构数组

c - 指向二维数组的指针作为c函数中的参数

java - 本周第一天在上一年,如何严格解析只有年和周数的日期?

c++ - 将值存储在链表的结构中

java - opencsv vs java 逗号分割

c - 具有等待队列挂起系统的Linux驱动程序代码

arrays - 并行排序数组

arrays - k-最大元素优化 Swift 3.0