【问题标题】:storing each word in a 2d string C将每个单词存储在二维字符串 C
【发布时间】:2021-01-16 10:24:52
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

    标签: c string getchar


    【解决方案1】:

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

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

    【讨论】:

    • 我明白了,但是当我打印出单词时,它也会打印出空格
    • @Moe 您还需要在 else 条件中添加对空间的检查。我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2017-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多