在C中将字符串设置为空字符串

时间:2019-04-08 18:22:57

标签: c

我想用C编写一个程序,该程序将接受输入的.txt文件,从中读取文件并应用函数或在stdout上显示文本或将其写入out文件。为了简单起见,我将其编写为仅显示单词。

完整代码:

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

int main(int argc, char **argv){

int c;

int output = 0;
FILE *infile;

while((c = getopt(argc, argv, "o:")) != -1){
    switch(c){

        case 'o':
            if(output){

                exit(EXIT_FAILURE);
            }
            output = 1;

            break;
        case '?':
            exit(EXIT_FAILURE);
        default:
            exit(EXIT_FAILURE);
    }
}

    for(; optind< argc; optind++) {
    infile = fopen(argv[optind], "r");


    size_t cpos = 0;
    char str[100];

    int ch;
    while((ch = fgetc(infile)) != EOF ) {
        if(ch == '\n' || ch == ' '){
            fprintf(stderr, "%s\n", str);
            str[0] = '\0';
            continue;
        } else{
            str[cpos++] = ch;
        }

    } 

    str[cpos] = 0;
    fprintf(stderr, "%s\n", str);

    fclose(infile);

    }
    exit(EXIT_SUCCESS);
    }

我的问题是while语句的一部分:

    for(; optind< argc; optind++) {
    infile = fopen(argv[optind], "r");

    size_t cpos = 0;
    char str[100];

    int ch;
    while((ch = fgetc(infile)) != EOF ) {
        if(ch == '\n' || ch == ' '){
            fprintf(stderr, "%s\n", str);
            str[0] = '\0';
            continue;
        } else{
            str[cpos++] = ch;
        }
    } 

    str[cpos] = 0;
    fprintf(stderr, "%s\n", str);

    fclose(infile);

    }

infile = fopen(argv[optind], "r")中,我正在保存argv中的文件名。在while语句中,我从infilefgetcEOF读一个字符。我想阅读每个字符,直到碰到空白行或空格。当我按下'\n'' '时,我想在stderr上显示该字符串,将String重置为空,并继续在下一行读取字符。否则ch将被放置在str[cpos]上(每个循环cpos递增)。在str[cpos]的末尾设置为0以标记字符串的结尾,最后的str被打印并关闭文件内。

问题:

如果我输入.txt文件(./program -o out.txt input.txt

word1
word2
word3

我所能得到的是

word1

我尝试将str[0]= '\0'设置为空字符串,但是之后str上没有存储任何内容。如何输出所有3个单词?

3 个答案:

答案 0 :(得分:2)

我看到了几个潜在的问题:

  1. 遇到空白时,您必须将cpos重置为零。
  2. 在循环中的fprintf之前,您应确保将当前str终止。
  3. 如果EOF之前的最后一个字符是\n,则将在末尾输出空白行。
  4. 我不知道您的数据集,但我仍然要注意输入的字符数不要超过99个,因为您第一次遇到100个或更多字符的单词时,可能会溢出缓冲区。

答案 1 :(得分:1)

您尚未对所构建的字符串进行零终止,也没有为下一个单词重置cpos = 0;

结果是,您将继续向str[]写入数据,而不是终止于此的'\0'

循环应如下所示:

while((ch = fgetc(infile)) != EOF ) {
    if(ch == '\n' || ch == ' '){
        str[cpos] = '\0';               // terminate this string
        fprintf(stderr, "%s\n", str);
        cpos = 0;                       // for next word
    } else{
        str[cpos++] = ch;
    }
} 

答案 2 :(得分:1)

当您知道str数组包含单词中的所有字符时,必须在数组后面附加一个终止符(零字节),并将cpos重置为0,然后再收集新单词的chars。

因此,假设str是{'w','o','r','d'} 而cpos是4 你做str [cpos] = 0 然后str是{'w','o','r','d',0} 那是一个正确的以零结尾的字符串

空字符串为{0},没错

无论如何不要忘记将cpos重置为0,否则您将在终止符之后进行写操作。

相关问题