所以程序应该执行以下操作:
要求用户输入字符串(字符串的最大长度为 250),一旦用户不输入任何内容(所以基本上按“回车”),程序停止输入并继续显示用户向后输入的每个字符串。
这是我的代码 - 一切正常,除了我无法进入while
底部的循环。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char userInput[250];
char *newSpace;
char *array;
int stringLength;
int inputElems = 0;
//Reset startingPtr back to where 'array' begins
char *startingPtr = array - inputElems;
// Sets endPtr to the last input element in the array
char *endPtr = startingPtr + inputElems;
do
{
puts("Please enter a string!");
// Gets input from user
fgets(userInput, 250, stdin);
// Finds out the number of characters the user entered
// + 1 to make room for the null character
stringLength = strlen(userInput) + 1;
// Allocate memory with the needed space
newSpace = malloc(stringLength);
// If malloc didn't allocate memory, display error
if (NULL == newSpace)
{
puts("Error!");
}
// Copy user input into array
strcpy(newSpace, userInput);
// Save input into array
array = newSpace;
// For testing purposes only, this line will be deleted once I can access the array
//puts("Here's what you wrote");
//printf("%s", array);
// Increase array
array++;
// Increase number of times user has input something
inputElems++;
} while(stringLength != 2);
//puts("Testing outside");
while (endPtr > startingPtr)
{
//puts("Testing inside");
--endPtr;
printf("%s", *endPtr);
}
free(newSpace);
}