我以前已经做到这一点了,但是当我实现功能时,我的字符给了我很多问题。我还检查了strlen是否显示正确的数字,但是显示出奇怪的东西。如果我输入一个10个字符长的字符,它将给我73个字符(最多7个字符,然后重新开始计数,因此14个字符将是77个字符)。第一个strncpy有效,但另一个不显示任何内容。
答案 0 :(得分:1)
只是为了使您步入正轨,我清理了您的代码。
#include<stdio.h>
#include<string.h>
#define MAX 100
void TestIfPalin(char *palindrome)
{
// TODO
printf("TestIfPalin(%s)\n", palindrome);
}
// Given a user-input string of the form "Command(argument)"
// split the string (by inserting \0 characters) into two parts
// and remove the brackets "()" from around the argument
void DetermineWhatCommand(char *userInput)
{
// look for the left-most '('
char *left_bracket = strchr(userInput, '(');
if (left_bracket != NULL)
{
// Seperate the command-name from the argument
*left_bracket = '\0';
// Look for the right-most ')' in the input
char *right_bracket = strrchr(left_bracket+1, ')');
if (right_bracket != NULL)
*right_bracket = '\0'; // remove the right bracket, it's not needed further
//else
// TODO - error? No finishing bracket
// Find the word passed to the function
char *argument = left_bracket+1;
if (strcmp(userInput,"Palin") == 0)
TestIfPalin(argument);
}
else
{
// No brackets - what sort of command is it?
// TODO - error message?
}
}
char *GetUserInput(char *userInput)
{
printf("> ");
fgets(userInput, MAX, stdin);
userInput[strcspn(userInput, "\n")] = '\0';
return userInput;
}
int main()
{
char userInput[MAX] = { '\0' };
char exitTest[] = "exit";
while(strcmp(exitTest, userInput) != 0)
{
GetUserInput(userInput);
if (strcmp(exitTest, userInput) != 0)
DetermineWhatCommand(userInput);
}
return 0;
}
功能应具有单个任务。 TestIfPalin()
不应寻找退出命令,getUserInput()
也不应寻找退出命令。
您正试图读入不存在的userInput
char *。确保您了解字符指针和字符数组之间的区别。字符数组,例如:
char userInput[MAX];
具有 MAX 个字符。而:
char *userInput;
没有空间,只是指向任何地方(可能为NULL,但这不能保证)。它需要指出要使用的东西。
char *userInput;
char buffer[MAX];
strcpy(buffer, "bananas"); // OK
strcpy(userInput, "empty!"); // FAILS
userInput = buffer; // userInput is now pointing at buffer
strcpy(userInput, "empty!"); // WORKS (overwrites 'bananas')