Click here to Skip to main content
15,881,092 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Can anyone help me in inputting strings on gcc compiler?
i want to input a string using string class
i used getline() but it didn't work.
what can i use to do so?
and also i want to input lines of strings to calculate no. of lines
so how can i do that?
i m new to gcc compiler please tell me what can i do?
thanks in advance....

Here is the sample code my original code is in my college i used the functions as follows:
using namespace std;
#include "iostream"
#include "string"
void temp()
{
    string s;
    getline(cin,s);//this didn't worked, it was skipped
    cout<<s; 
}

int main()
{
        string s;
        getline(cin,s);   //This function worked
        temp();
        return 0;
}

this is just the sample code when i call getline(cin,s) inside main() it works and allow me to input a sentence
but problem is when i call it inside any function other than main() it doesn't work.
Posted
Updated 18-Feb-13 23:21pm
v4
Comments
Fredrik Bornander 18-Feb-13 5:50am    
Show us how you used getline() so that we can tell you why it didn't work.
enhzflep 18-Feb-13 7:00am    
If you want to use the std::string class, you should be using cin.
I.e
string yourStringVar;
cout << "Enter a string: ";
cin >> yourStringVar;
cout << "you entered: " << yourStringVar;
Member 8536324 18-Feb-13 9:58am    
it accepts only one word sir
Member 8536324 18-Feb-13 9:56am    
Sir, I used getline like getline(cin,Stringvariable);
Member 8536324 18-Feb-13 9:58am    
Actually it worked but only in main() if i use it inside any member function of class it doesn't work and not even in member functions but also in non-member functions it didn't work.

Your function temp accepts a string into a temporary variable. Then, when it returns to main the temporary variable s goes out of scope and is destroyed. You code should be:
C++
string temp()
{
    string s;
    getline(cin,s);//this didn't worked, it was skipped
    return s;
}
 
int main()
{
    string s;
    s = temp();   //This function should now work
    return 0;
}
 
Share this answer
 
Comments
Member 8536324 19-Feb-13 5:35am    
ok i will try
thanks a lot
Use getline(cin, s, '\n');

C++
do
{
    getline(cin, s, '\n');

    // Process the line
    ....
}
while (s.length() > 0);
 
Share this answer
 
v2
Comments
Member 8536324 19-Feb-13 5:35am    
thanks a lot sir
Member 8536324 19-Feb-13 5:35am    
i will try

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900