Get string from console but don't know the length - c++

I am asking the user to input a string on console. But I don't know the length of string.
How can I define a structure to fit the input with variable length?
int main(){
int i;
char s[10];
cout << "input string:";
cin >> s;
return 0;
}
The sample code will cause heap corruption if the input string length exceeds 10.

Use std::string instead. For example:
#include <string>
std::string s;
std::cout << "input string:";
std::cin >> s;
Or use std::getline to get a line until endline character
std::getline(std::cin, s);

In c++, you should use std::string instead of char[], especially for variable length strings.

This is a working, general example that allows you to read in strings including white space:
#include <string>
#include <iostream>
int main()
{
std::string s;
std::cout << "Type a string\n";
std::getline(std::cin, s);
std::cout << "You just typed \"" << s << "\"\n";
}

cplusplus.com says that the >> operator for strings from an input stream uses whitespaces as a seperator. so if you need your string to be able to contain whitespaces you have to use std::getline(...) (wich is different from istream::getline(...)!!!!)
basically it goes like this:
std::string inputString;
std::getline(cin, inputString);
my answer was inspired by this answer

#include <iostream>
#include <string>
using namespace std;
int main(){
int i;
string s;
cout << "input string:";
cin >> s;
return 0;
}
Use std::string instead of char[].
If you need to use char[] after the input, you can refer to these questions:
std::string to char*
convert string to char*
For example,
string s1;
cin >> s1;
char *s2;
s2 = new char[s1.length() + 1]; // Including \0
strcpy(s2, s1.c_str());
delete []s2;
You can use malloc and free if you don't know about new and delete.

Basically it is suggested that you should always std::string to get variable length input. Still if you need to store the input in an array to pass it to a function or something. you can go for this. Though its quite lame.
/* #include <string> */
std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;
Regards
Genocide_Hoax

Related

How to read whitespace chars from text file? [duplicate]

#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

how do i include whitespaces for input to struct array from file [duplicate]

#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

Program to remove all special characters from an input string and store alphabets in a new string [duplicate]

#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

c++ string.length() and casting string to char arrays not working properly? [duplicate]

#include <string>
std::string input;
std::cin >> input;
The user wants to enter "Hello World". But cin fails at the space between the two words. How can I make cin take in the whole of Hello World?
I'm actually doing this with structs and cin.getline doesn't seem to work. Here's my code:
struct cd
{
std::string CDTitle[50];
std::string Artist[50];
int number_of_songs[50];
};
std::cin.getline(library.number_of_songs[libNumber], 250);
This yields an error. Any ideas?
It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".
Use std::getline:
#include <string>
#include <iostream>
int main()
{
std::string name, title;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your favourite movie: ";
std::getline(std::cin, title);
std::cout << name << "'s favourite movie is " << title;
}
Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.
Update
Your edited question bears little resemblance to the original.
You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.
You have to use cin.getline():
char input[100];
cin.getline(input,sizeof(input));
The Standard Library provides an input function called ws, which consumes whitespace from an input stream. You can use it like this:
std::string s;
std::getline(std::cin >> std::ws, s);
Use :
getline(cin, input);
the function can be found in
#include <string>
You want to use the .getline function in cin.
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
Took the example from here. Check it out for more info and examples.
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow.
If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
THE C WAY
You can use gets function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
I rather use the following method to get the input:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string name;
cout << "Hello, Input your name please: ";
getline(cin, name);
return 0;
}
It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

c++ unable to get proper string input

I am new to programming just wrote this simple function to calculate length of a string but I am unable to take input string from the user properly(have tried my alternatives).
/////////Function to calculate length of a string////////////////////
void str_length(){
char str[30];
int counter=0;
cout << "Enter string: ";
gets(str);
//cin.getline(str,256);
//cin >> str;
for(int i=0;str[i] != '\0';i++){
counter++;
}
cout << "String length is: " << counter << endl;
}
///////////////////////////////////////////////////////////////
of all possible ways the program either exits abruptly or with 'cin' I can only get partial string till the first space.
If you tried cin.getline(str,256), you'd have needed your buffer to be declared as char str[256].
You shouldn't really be involving yourself with these things however. Stick with std::string:
std::string str; // Declare a string
std::getline(std::cin, str); // Get a line from the std::cin stream and put it in str
unsigned int stringLength = str.length(); // get the length of the string
Why not use the std::string library. It is nice and easy to use.
void str_length()
{
std::string line;
std::cout << " Please input current line: " << std::endl;
std::getline(std::cin, line);
std::cout << "the length of input string is: " << line.length() <<std::endl;
}
I can only agree with my previous speakers and would recommend you to use the better variant by using std::string. Nevertheless if you really want to use C-String than you can use this approach:
std::cin.get(char *s, streamsize n)
This method reads in characters until you press the enter button.
#include<iostream>
#define SIZE 40;
using namespace std;
int main() {
char str[SIZE];
cin.get(str, SIZE-1);
cout << str << endl;
return 0;
}
You should be aware if you have once created an buffer overflow that you will get some trouble at the next call of this method. The problem is that your input buffer will save the remaining characters and at the next call your methods will only read in the remaining characters. To solve this problem you have to clear your input buffer before each input.
Best practice is to use this code in front of each cin.get()
while(cin.get() != '\n');
#include <iostream>
void str_length(){
char str[30];
std::cout<< "Enter string: ";
std::cin>>str;
int counter=0;
for(counter=0;str[counter] != '\0';counter++){}
std::cout<<"String length is "<<counter<<std::endl;
}
OR
#include <iostream>
#include <string>
void str_length(){
std::string str;
std::cout<<"Enter string: "<<std::endl;
std::cin>>str;
std::cout<<"String length is "<<str.size()<<endl;
}