将每个单词存储在 2d 字符串 C 中

问题描述

我想将每个单词存储在一个二维字符串中。我写的代码没有错误,唯一的问题是当有两个或更多空格时,它将空格存储为一个单词。如果有人知道我该如何解决这个问题

这是我的代码:

#include <stdio.h>
#include <ctype.h>
#define IN  1
#define OUT 0

int main()
{
    char words[100][1000];
    int i=0,k,j=0,m=0;
    int state = OUT;
    int nw = 0;


    while((k = getchar()) != EOF)
    {
        if((isspace(k)!= 0)|| (ispunct(k)!= 0))
        {
            state = OUT;
            words[i][j] = '\0';
            i++;
            j = 0;
        } 
        else
        {
            words[i][j++]= k;
            if(state == OUT)
            {
                state = IN;
                nw++;
            }
        }
    }
    
    
    return 0;
}

解决方法

在输入新单词之前,您需要通过考虑最后一个字符来跳过所有空格。您还可以简化对空格和标点符号的检查。

#include <stdio.h>
#include <ctype.h>
#define IN  1
#define OUT 0

int main()
{
    char words[100][1000];
    int i=0,k,j=0,m=0;
    int state = OUT;
    int nw = 0;

    int last_char = ' ';
    while((k = getchar()) != EOF)
    {
        if((isspace(k)|| ispunct(k)) && !isspace(last_char))
        {
            state = OUT;
            words[i][j] = '\0';
            i++;
            j = 0;
        } 
        else if (!isspace(k))
        {
            words[i][j++]= k;
            if(state == OUT)
            {
                state = IN;
                nw++;
            }
        }
        last_char = k;
    }
    
    
    return 0;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...