Scanf在C中没有正确读取字符串。出了什么问题?

时间:2015-12-04 00:11:35

标签: c arrays string function scanf

我正在编写一个代码,该代码应该在字符串中找到空格,并在不同的字符串数组中将它们之前和之后的部分分开。第一个问题是scanf甚至没有正确地读取我的字符串,但是我之前没有使用C中的字符串,并且好奇它是否正确(特别是对于a []数组)。

char expr[50];
char *a[50];
scanf("%s",expr);
int i=0;
int j=0;

while (strlen(expr)!=0){
    if (expr[i]==' '){
        strncpy(a[j],expr,i);
        strcpy(expr,expr+i+1);
        j++;
        i=0;
    }
    else {
        if (strlen(expr)==1){
            strcpy(a[j],expr);
            strcpy(expr,"");
            j++;
            i=0;
        }
        else i++;
    }

}

i=0;

for (i=0; i<j; i++){
    printf("%s\n",a[i]);
}
return 0;

2 个答案:

答案 0 :(得分:1)

这段代码错了。

首先,请勿使用未初始化的a[j]

添加

if((a[j]=calloc(strlen(expr)+1,sizeof(char)))==NULL)exit(1);

strncpy(a[j],expr,i);strcpy(a[j],expr);之前分配一些内存。

辅助,strcpy(expr,expr+i+1);错误,因为strcpy()不接受重叠区域。

最后,如果scanf("%49s",expr);使用scanf("%s",expr);,则应使用LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES += \ librtmp/amf.c \ librtmp/hashswf.c \ librtmp/log.c \ librtmp/parseurl.c \ librtmp/rtmp.c LOCAL_CFLAGS := -D__STDC_CONSTANT_MACROS -DNO_CRYPTO LOCAL_LDLIBS := -llog LOCAL_MODULE := librtmp include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := dump LOCAL_CFLAGS := -DRTMPDUMP_VERSION=\"v2.4\" LOCAL_LDLIBS := -llog LOCAL_SRC_FILES := dump/rtmpdump.c LOCAL_C_INCLUDES := $(LOCAL_PATH)/../librtmp LOCAL_C_INCLUDES += dump/rtmpdump.h LOCAL_STATIC_LIBRARIES := librtmp include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := test LOCAL_SRC_FILES := nelly.c nelly_tables.c RTMPClient.c LOCAL_LDLIBS := -llog LOCAL_SHARED_LIBRARIES += dump include $(BUILD_SHARED_LIBRARY) 以避免缓冲区溢出。

答案 1 :(得分:0)

  1. 请勿使用scanf,使用gets()进行标准输入,或使用fgets()进行FILE*

  2. 阅读
  3. 要将字符串分解为以空格分隔的元素,只需使用 strtok ():

  4. char expr[50];

    gets(expr);
    
    char* a[50];
    int i;
    
    for (i = 0; i < 50; i++)
    {
        a[i] = (char*)malloc(10); // replace 10 with your maximum expected token length
    }
    
    i = 0;
    
    for (char* token = strtok(expr, " "); token != NULL; token = strtok(NULL, " "))
    {
        strcpy(a[i++], token); 
    }
    
    for (int j = 0; j < i; j++)
    {
        printf("%s\n", a[j]);
    }
    
    
    // don't forget to free each a[i] when done.
    

    gets(expr); char* a[50]; int i; for (i = 0; i < 50; i++) { a[i] = (char*)malloc(10); // replace 10 with your maximum expected token length } i = 0; for (char* token = strtok(expr, " "); token != NULL; token = strtok(NULL, " ")) { strcpy(a[i++], token); } for (int j = 0; j < i; j++) { printf("%s\n", a[j]); } // don't forget to free each a[i] when done.

    1. 为简单起见,此示例使用弃用的函数,例如 ,请考虑将其替换为 strcpy