2015-04-29 51 views
-2

这段代码的主要目标是捕获用户的输入,并对我所提供的选择做任何他想做的事情,但是我被卡住了:当我编译时,我只能键入单词并且程序停止工作。为什么我的程序在输入时停止工作?

我不知道我在哪里犯了一个错误。

的是我的代码:

#include <stdio.h> 
#include <string.h> 
#define MAX_STRING_LENGTH 100 

void grab_user_input(void); 
void load_menu(void); 
void Count_the_letters(void); 

int main(void) 
{ 
    grab_user_input(); 
    return 0; 
} 

void grab_user_input(void) 
{ 
    char word; 
    { 
     printf("Please enter a single word (25 characters or less): \n"); 
     scanf("%s", &word); 
     printf("Thanks! The word you entered is: %s\n", word); 
    } 

    void load_menu(void) 
    { 
     int choice; 
     do 
     { 
      int choice; 
      printf("\n(:===Menu====:)\n"); 
      printf("1. Count_the_letters\n"); 
      printf("2. Count_the_vowels\n"); 
      printf("3. Reverse_the_word\n"); 
      printf("4. Check_if_palindrome\n"); 
      printf("5. Enter_a_new_word\n"); 
      printf("6.  Exit\n"); 
      scanf("%d", &choice); 
      switch (choice) 
      { 
      case 1: Count_the_letters(); 
      break; 

      } 
     } while (choice != 3); 
    } 

    void Count_the_letters(void) 
    { 
     char S[MAX_STRING_LENGTH]; 
     int count; 

     count = 0; 

     do { 
      printf("string:\t"); 
      scanf("%s",S); 
      if (strcmp(S,"exit") != 0) 
       ++count; 
     } while (strcmp(S,"exit") != 0); 

     printf("word count:\t%d\n", count); 
    } 

    return 0; 
} 
+1

是你的确切代码?你从哪里学习c? –

+0

是多数民众赞成我的代码即时学习代码由我自@iharob –

回答

2
scanf("%s", &word); 

需要字符数组来读取数据。 &word只有一个字符的空间。

您正遇到未定义的行为。

使用

char word[26]; 
scanf("%25s", &word); 
+0

谢谢@ R Sahu它的工作,我真的appeciated。 –

0

的原因是要传递的地址给你声明的变量charscanf()试图写两个字节,其中只适合一个。

char word 

此声明一个char变量,它可以容纳一个字节

scanf("%s", &word); 

whill需要用于空字符串'\0'至少一个字节。

而且,你在void grab_user_input(void)里声明了很多函数,那是不是有效的标准c,它可能适用于某些编译器,但它不是标准的。

相关问题