+ 1

Extra-Terrestrials task

https://code.sololearn.com/cppAL9w1bknG/?ref=app What is wrong with my code? Why can’t I output a reversal word correctly without those strange characters before it?

19th Jan 2021, 4:05 PM
Jordana Barcelos Viana
Jordana Barcelos Viana - avatar
11 Respostas
+ 2
#include <stdio.h> int main() { char a[100],b[100]; int start,end,count=0; gets(a); while(a[count]!='\0') { count++; end=count-1; } for(start=0;start<count;start++) { b[start]=a[end]; end--; } b[start]='\0'; printf("%s",b); return 0; }
21st Jan 2021, 12:36 PM
Kalindu Wanasinghe
Kalindu Wanasinghe - avatar
+ 4
Here is my suggestion In C++ #include<iostream> #include<bits/stdc++.h> using namespace std; int main(){ string a,b; cout<<"Enter the string: "; cin>>a; b=a; reverse(b.begin(),b.end()); cout<<b; return 0; } (//Note:- when you type this code in sololearn,plz remove cout<<"Enter the string: ")
21st Jan 2021, 3:24 AM
Kalindu Wanasinghe
Kalindu Wanasinghe - avatar
+ 4
đŸ€—đŸ€—
26th Jan 2021, 12:07 PM
Kalindu Wanasinghe
Kalindu Wanasinghe - avatar
+ 3
This is the answer in C
21st Jan 2021, 12:36 PM
Kalindu Wanasinghe
Kalindu Wanasinghe - avatar
+ 3
As shown above in my code,first you can take the string as array of characters and then you can print it.next you can declare a variable called end and you can use a for loop by initializing the end value as the last member of the array.
21st Jan 2021, 12:43 PM
Kalindu Wanasinghe
Kalindu Wanasinghe - avatar
+ 2
Ok, don't worry, this is what the code is doing: Input - > chars[0] chars[14] - > output Input - > chars[1] chars[13] - > output ... And so on But as you can see, at the time you read them, char[14], char[13] ecc. are not initialized yet So you are actually reading garbage data. When this garbage data goes in output you will get strange char and even sounds
19th Jan 2021, 4:30 PM
Angelo
Angelo - avatar
+ 1
I will use the socratic method: What is the value of chars[14], when you have only initialized chars[0]?
19th Jan 2021, 4:16 PM
Angelo
Angelo - avatar
+ 1
You should first read the entire word ( scanf("%s", chars) ) and then reversing the array
19th Jan 2021, 4:32 PM
Angelo
Angelo - avatar
+ 1
Angelo ohh, that makes all sense, thank you very much!
19th Jan 2021, 4:33 PM
Jordana Barcelos Viana
Jordana Barcelos Viana - avatar
+ 1
Kalindu Wanasinghe excellent, bro, thank you!
21st Jan 2021, 8:55 PM
Jordana Barcelos Viana
Jordana Barcelos Viana - avatar
0
Angelo sorry, still didn’t get it
19th Jan 2021, 4:24 PM
Jordana Barcelos Viana
Jordana Barcelos Viana - avatar