C程序读取和存储字符串 [英] C program to read and store strings

查看:101
本文介绍了C程序读取和存储字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写在C片code的迭代访问牛逼次,每次需要输入,并会进行一些计数操作(计数每个单词的长度)小曲儿的文本。现在我只是测试,如果输入的工作,它没有。

I'm writing a piece of code in C that iterates T times and each time takes as input the text of a little song on which it will perform some counting operation (counting the length of each word). For now I'm just testing if the input works, and it doesn't.

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

#define MAX_SONG_SIZE 501

int main(void){
    int T;
    scanf("%d", &T);
    while(T--){
        char* song = malloc(MAX_SONG_SIZE);
        if(song == NULL){
            printf("malloc failed");
            return 1;
        }
        fgets(song, MAX_SONG_SIZE, stdin);
        printf("foo\n");
        free(song);
    }
    return 0;
}

我使用的与fgets(),因为这些单词之间的空格,动态内存分配,因为我不能只使用一个阵列中的所有歌曲,角色从previous迭代将保持数组中为止。

I'm using fgets() because of the spaces among the words, and dynamic memory allocation because I can't just use one array for all the songs, characters from the previous iteration would remain in the array.

但有一个问题。它会跳过在与fgets()在第一次迭代,只写福,没有等我插入一个字符串。

But there's a problem. It skips the fgets() in the first iteration, writing only "foo" and without waiting for me to insert a string.

这是它如何与初始输入3打印为例:结果
3结果
foo的结果
这是一个测试结果
foo的结果
另一个测试结果
富结果

This is an example of how it prints with initial input "3":
3
foo
this is a test
foo
another test
foo

通过替换的printf(富\\ n); 的printf(&LT;&LT;%S&GT;&GT; \\ N,曲); 的输出是这样的:

With substituting printf("foo\n"); with printf("<<%s>>\n", song); the output is this:

3<br>
<< <br>
>> <br>
test <br>
<<test <br>
>> <br>
another test <br>
<<another test <br>
>> <br>

我该如何解决这个问题?如果你的任何建议欢迎您。

推荐答案

有一个 \\ n 留在输入缓冲器,看到的 http://c-faq.com/stdio/scanfinterlace.html

There's a \n left in the input buffer, see http://c-faq.com/stdio/scanfinterlace.html

从链路A报价:

作为一般规则,你不应该试图调用交织一起scanf函数
  调用得到()(或任何其他输入例程); scanf函数特有的
  治疗换行符几乎总是导致麻烦。无论是使用scanf函数
  读什么都不要。

As a general rule, you shouldn't try to interlace calls to scanf with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf to read everything or nothing.

这篇关于C程序读取和存储字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆