繁体   English   中英

C读取用户输入的数据

[英]C Reading user entered data

我正在尝试编写一个简单的程序,将用户输入的字符串读入指针数组。 读数很好,但是当我想在方法中添加一个额外的参数以节省实际读取的字符串数时,它将停止工作。 编译器不是很有帮助,所以我决定在这里解决我的问题。

实际代码:

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

void read(char**, int *);
void write(char**);

int main() {
    int amount = 0;
    int * amount_p = &amount;
    char *pt_p[1000];
    read(pt_p,amount_p);
    write(pt_p);
}


void read(char ** pt, int * amount) {

    char  stop[] = "STOP";
    char* woord;
    int i = 0;

    printf("Enter a word: ");
    scanf("%70s", woord);
    pt[i] = malloc(sizeof(char)*(strlen(woord)+1));
    pt[i] = strcpy(pt[i], woord);

    i++;

    while(strcmp(stop,pt[i-1]) != 0) {
          printf("Enter a word: ");
          scanf("%70s", woord);
          pt[i] = malloc((strlen(woord)+1)*sizeof(char));
          pt[i] = strcpy(pt[i], woord);
        i++;    
    }
    *amount = i;

}

void write(char ** pt) {
    int i = 0;
    char  stop[] = "STOP";
    while(strcmp(stop,pt[i]) != 0 ) {       
        printf("pt[%d]-> %s",i,pt[i]);
        printf("X \n");
        i++;
    }

}

您需要分配一些空间来输入字符串

char* woord; 只是声明一个没有特别指向的指针。

而是声明为

char woord[128];

在堆栈上分配128个字节供您输入。

还可以使用fgets()而不是scanf()来读取字符串,这样可以防止用户输入太大的字符串。

if ( fgets( woord, sizeof(wooord), stdin ) != NULL )
{
  char* p = strchr( woord, '\n' );
  if (p != NULL ) 
  {
    *p = '\0';
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM