I want to use scanf() to read the input string.
If the input of printf("Enter start word: "); is the symbol #, it will not execute the next printf("Enter end word: "); command, and if the input is a word, then it will execute the next command. But I don't know how to determine whether the input is a symbol or a word.
Whatever I input, it still executes printf("Enter end word: ");
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX_WORD_LENGTH 32
#define FORMAT_STRING "%31s"
#define VERY_HIGH_VALUE 999999
char **InputWords(int *n, char *start, char *end) {
printf("Enter a number: ");
scanf("%d", n); // the number of the input words
char **words = malloc(sizeof(char *) * *n);
assert(words != NULL);
for (int i = 0; i < *n; i++) {
// allocate memory for the length of each input word
words[i] = malloc(sizeof(char) * MAX_WORD_LENGTH);
assert(words[i] != NULL);
printf("Enter a word: ");
scanf(FORMAT_STRING, words[i]);
}
printf("Enter start word: ");
if (scanf("%s", start) == 1) {
printf("Enter end word: ");
scanf("%s", end);
};
printf("\n");
printf("%d, %s, %s", *n, start, end);
return words;
}
int main(void) {
int n;
char start, end; //the start/end word, which is not necessary in stage 1-4
char **words = InputWords(&n, &start, &end); //create an array to store all input words
return 0;
}
Moreover, when I add the code printf("%d", n); at the end of the function, the value of n becomes 0, although my input n is other number.
When I add printf("%d, %s, %s", *n, start, end); at the last, the output shows
Enter a number: 3
Enter a word: bad
Enter a word: ban
Enter a word: dad
Enter start word: bad
Enter end word: ban
110, an, ban
But in my input, the n = 3, start = ban and end = ban
scanf("%s", start)This is wrong.startpoints to a singlecharinstead of a buffer for a string. Same forend.startandendare pointers tochar, but they are not really strings; each points to a single character inmain.scanf("%s")` can only scan words of non-zero length, but since it must store the null terminator, one char isn't enough. Use a reasonably sized array of chars, which should be a local variable ofInputWords.