0

Problem with spaces and other signs in this code..

this code is used to print nxt alphabet from already present in array. But it is printing "!" sign for spaces and not printing question mark sign...how to fix it? #include <iostream> using namespace std; int main() { char a[20]; char msg[] = "aaa aaa ???"; for (int i = 0; i<11; i++) { a[i] = msg[i]+1; cout << a[i]; } }

2nd Jan 2021, 7:52 AM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar
4 ответов
+ 4
If you want to print only for alphabet to print next alphabet ,then you can do like that: https://code.sololearn.com/ca23A1A89a13
2nd Jan 2021, 8:19 AM
The future is now thanks to science
The future is now thanks to science - avatar
+ 2
The problem in the first line of the loop `a[i] = msg[i] + 1` Let's assume msg[i] is a space. Now characters are represented as numbers in the computer, specifically 32 for space. When you add a number to char, it is as of you are adding a number to a number. So when you do msg[i] + 1 you are actually doing 32 + 1 Now when you assign 33 to a[i], it is converted back to char. The number 33 is for '!', and that is why when you print a[i], ! is printed. The fix to the problem is simple, just move the + 1 inside the square brackets, that is, change the line to a[i] = msg[i + 1]; But why are you using another character array `a`? Instead of doing `a[i] = msg[i + 1]; cout << a[i];` You can just do `cout << msg[i + 1];` Another suggestion, you can use the `string` class instead of using character arrays too https://en.cppreference.com/w/cpp/string/basic_string
2nd Jan 2021, 8:15 AM
XXX
XXX - avatar
+ 1
Zatch bell Thanks
2nd Jan 2021, 8:22 AM
Muhammad Ali Zulfiqar
Muhammad Ali Zulfiqar - avatar
0
you can for example add if statement in the for loop to check if msg[i] is letter or not
2nd Jan 2021, 8:14 AM
Michal Doruch