将char数组传递给c中的scanf函数

时间:2019-11-17 19:21:48

标签: c scanf

我在C代码中具有以下功能

char text[4000] = "some text here";
analyze_text(text);

在主函数中,我想向其传递一些字符串。如果我做这样的事情

char text[4000];
scanf("%s",text);
analyze_text(text);

这很酷,可以实现目标,但是我想提供一些用户输入,但是我不确定如何从中获取char []。我尝试了以下2种方法,但它们似乎都不起作用:

char text[4000];
int c;
int count=0;
c = getchar();
count = 0;
while ((count < 4000) && (c != EOF)) {
    text[count] = c;
    ++count;
    c = getchar();
}
analyze_text(text);

OR

void analyze_text(char text[]) {
    int printable_text_length = 0;
    int text_length = strlen(text);
    int word_count = 0;
    int sentence_count = 0;
    int in_sentence = 0;
    int in_word = 0;
    int count[ASCII_SIZE] = { 0 };
    for (int i = 0; i < text_length || text[i] != '\0'; i++) {
        int c = text[i];
        if (!isspace(c)) {
            printable_text_length++;
        }
        if (isalpha(c)) {
            in_word = 1;
            in_sentence = 1;
            count[tolower(c)]++;
        }
        if (text[i] == ' ' && text[i + 1] != ' ' && in_word==1) {
            word_count++;
            in_word = 0;
        }
        if (text[i] == '.' && in_sentence==1) {
            sentence_count++;
            in_sentence = 0;
        }
    }
    if (in_word == 1) { word_count++; }
    if (in_sentence == 1) { sentence_count++; }

    char charIndexes[ASCII_SIZE];
    for (int i = 97; i <= 122; i++) {
        charIndexes[i] = i;
    }
    for (int i=97; i <= 122; i++) {
        for (int j = i + 1; j <= 122; j++) {
            if (count[i] > count[j]) {
                int temp = count[j];
                count[j] = count[i];
                count[i] = temp;
                int temp2 = charIndexes[j];
                charIndexes[j] = charIndexes[i];
                charIndexes[i] = temp2;
            }
        }
    }
...printf...
}

我知道第一个应该返回指向char数组的指针,但是第二个应该返回char数组本身吗?

距离我使用c / c ++已有10年了。有人可以给我一些提示吗?

更新(整个功能):

{{1}}

2 个答案:

答案 0 :(得分:2)

问题

char text[4000];
scanf("%s",text);
analyze_text(text);

scanf标识以空格分隔的块,因此您只会读取第一个。

为了从用户那里读取整行内容,请尝试fgets

char text[4000];
fgets(text, 4000, stdin);
analyze_text(text);

您可能需要检查fgets的返回值以进行错误检测。

答案 1 :(得分:1)

您可以使用char的动态数组将其传递给函数。 这是代码

#include <stdio.h>
#include <stdlib.h> 
void analyze_text(char* text) {


    for (int i = 0; text[i] != '\0'; i++) {
        printf("%c\n",text[i] );
    }
}
int main() {

    char* text  = (char *)malloc(4000 * sizeof(char));
    scanf("%s", text);
    analyze_text(text);
    return 0;
}

这是输入为'abhishek'的输出

a
b
h
i
s
h
e
k

请记住,dyanamc数组中的strlen不会给出输入数组的长度。