Reputation: 1
I have this, when I put the function in main the input is 'hello' and the output is 'ello'.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void getString() {
char enter;
printf("Type input below");
scanf("%c", &enter);
system("cls");
}
void scanString () {
char target[100];
scanf("%s", &target);
printf("%s", target);
}
int main () {
getString();
scanString();
}
Upvotes: 0
Views: 738
Reputation: 19
If you omit
scanf("%c", &enter);
system("cls");
and correct your scanf statement for the string like below
scanf("%s", target); /* no need to use & with an array */
your code will work as you expect.
For more help, try my channel on YouTube, "Computing Foundations". I love helping beginners. https://www.youtube.com/channel/UCAZFaacJMNRm3JIn3nNR1cQ
Upvotes: 0
Reputation: 1
void getTarget () {
char target[100];
printf("Type input below and press ENTER");
scanf("%99s", &target);
}
I moved the call to scanf to the same function where the user enters it so the variable is set when the user presses enter, not after.
Upvotes: 0
Reputation: 155363
Your getString
is explicitly eating a single character from stdin
with scanf("%c", &enter)
and ignoring it, so the second scanf
in scanString
doesn't receive that character. From the names used, it seems like you think you're consuming a newline the user already put in stdin
, but in fact, the user is not entering a newline, they just enter hello
, and you consume and discard the h
, clear the screen, then consume and print the ello
.
Upvotes: 1