[SOLVED] Unexpected return from cin.getline() in C++ | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 5

[SOLVED] Unexpected return from cin.getline() in C++

I have this problem that when I use getline() function to input a char array it also inserts other characters, that are not constant and change every time I run the program. I do realize it is most likely because of some kind of overflow happening, and it just takes numbers from the RAM. But is there a possibility to fix that? (Program is supposed to reverse a string and remove any non-letters, excluding spaces) Here is my program: #include <iostream> #include <ctype.h> #include <string> using namespace std; int main() { string decoded = ""; char text[100]; cin.getline(text,sizeof(text)); for(int i = sizeof(text)-1; i >= 0; i--){ if (isalpha(text[i]) || text[i] == ' ' ) decoded.push_back(text[i]); } cout << decoded; return 0; }

4th Aug 2021, 7:42 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
4 ответов
+ 6
The stray characters you are getting were not inserted by the getline call, but rather what is original stored within the memory locations now allocated to and held by your character array. Notice that the garbage values no longer appear if you initialize the array and overwrite all values held by those slots. char text[100]{};
4th Aug 2021, 8:08 AM
Fermi
Fermi - avatar
+ 6
You're welcome! Extra references: https://en.cppreference.com/w/c/language/array_initialization "In C, the braced list of an initializer cannot be empty. C++ allows empty list: int a[3] = {0}; // valid C and C++ way to zero-out a block-scope array int a[3] = {}; // invalid C but valid C++ way to zero-out a block-scope array"
4th Aug 2021, 8:12 AM
Fermi
Fermi - avatar
+ 5
Thanks a tone bro!
4th Aug 2021, 8:10 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 1
I think it's good practice to use the function ( cin.ignor(); ) this well make the programm work well
12th Aug 2021, 11:40 AM
Anas Mohammed Sarhan Saif
Anas Mohammed Sarhan Saif - avatar