Reputation: 13
For my homework, part of what I need to do is take a phrase from the user, and from there take only the letters in the phrase, ignoring numbers, spaces, and special characters. Once I find letters in the string, I need to store them into a separate variable. However, I can't get that variable to store anything outside of the if
statement that looks for letters.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string line, temp;
cout << "Enter phrase to check: ";
getline(cin, line);
for(int i = 0; i < line.size(); i++)
{
if((line[i] > 64 && line[i] < 91) || (line[i] > 96 && line[i] < 123))
{
temp[i] = line[i];
}
}
cout << temp;
return 0;
}
When I run the program, temp
outputs nothing. But I know the if
statement is correctly finding letters, from making it print line[i]
inside the if
statement.
Upvotes: 1
Views: 64
Reputation: 1602
The way you're currently doing it (temp[i] = line[i];
) means that each non special character in line will be placed at the same index in temp. This should usually fail since temp (a string
) does not resize on indexing.
For changing the size of a string, there exists a function called string::push_back
as detailed here.
Instead of indexing using temp[i]
, you would instead use temp.push_back(line[i]);
This function allows the string to resize itself to accommodate the new char if need be and won't throw a segmentation fault.
NB: std::string::push_back
is designed to append a single char to a string. There exist multiple other ways of doing this, including Nikita Demodov's answer which shows the use of the +=
operator which is much more lenient and will allow appending of other strings etc. push_back
is most common to the std::vector where it is used to append single items to the list.
Upvotes: 0
Reputation: 571
your temp
variable is an empty string. temp[x]
is telling the compiler to change the x
-th character of that string(which doesn't make any sense, as the string doesn't have any characters!). You're lucky(or unlucky) that you aren't getting any Segmentation faults(crashes).
Just use the +=
operator:
temp += line[i];
Upvotes: 3