I am trying to create a reversed string using getchar() to first read a string in array format. I did not write the reversing part yet. The code works for any strings without space. Ex. "HelloWorld!" will output "HelloWorld!" but "Hello World!" will only output "Hello".
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
char temp;
char my_strg[MAX_SIZE];
int length;
printf("Please insert the string you want to reverse: ");
scanf("%s", my_strg);
while((temp = getchar()) != '\n')
{
my_strg[length] = temp;
length++;
}
printf("%s\n", my_strg);
return 0;
}
Your issue is scanf
. scanf
only reads until whitespace is encountered. To fix this, you can use fgets
(and strcspn
to remove the newline):
if(fgets(my_strg, sizeof(my_strg), stdin) == NULL)
{
perror("fgets");
return EXIT_FAILURE;
}
my_strg[strcspn(my_strg, "\n")] = '\0';
Or with scanf
...
if(scanf("%99[^\n]", my_strg) != 1)
{
fprintf(stderr, "scanf() failed to read\n");
return EXIT_FAILURE;
}
After these changes you can entirely remove your getchar
loop.
In your program you need to check for I/O errors. I've shown you how to do this above. If you don't do this, your program could give incorrect output or in certain cases cause undefined behavior (which usually results in a crash).
Bonus: here's how to reverse a string:
size_t l = strlen(my_strg) / 2;
char *s = my_strg, *e = s + l;
while(l--)
{
char tmp = *--e;
*e = *s;
*s++ = tmp;
}
Your program has undefined behaviour , since you are attempting to access an element of an array, my_strg[length]
with an unitialized value of length
.
To fix this, move your declaration of length
to after the scanf
call and initialize it to the length of the string that scanf
reads:
scanf("%s", my_strg);
size_t length = strlen(my_strg);
Alternatively, drop the scanf
call completely and initialize length
to zero:
char my_strg[MAX_SIZE] = { 0, }; // Note: make sure you ALSO initialize your array!!
printf("Please insert the string you want to reverse: ");
size_t length = 0;
while ((temp = getchar()) != '\n') {
//..
Note: If you (for some reason) don't want to initialize your entire array to zeros (as the first line in my second code block will do), then make sure to add a zero ( nul
) character at the end of the string, before printing it (or doing anything else with it). You could simply add this line after the while
loop:
my_strg[length] = '\0'; // "length" will already point to one-beyond-the-end
EDIT: To address the very good points made by David C. Rankin in the comments section, you could (should) improve your while
loop control to: (a) prevent buffer overflow and (b) handle input error conditions. Something like this:
while ((length < MAXSIZE - 1) && (temp = getchar()) != '\n' && temp != EOF) {
//..
but the exact tests and controls you use would depend on how you wish to handle such issues.
By definition, scanf("%s", my_strg)
reads a string until the first white space (and a blank counts as white space). So "Hello world"
will be read until the first blank, ie my_strg
will contain "Hello"
then. To read until a new line (including the newline), use fgets
.
BTW: variable length
is uninitialized, such that you get undefined behaviour.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.