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;
}
Related
#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.
#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.
I'm working on homework for my c++ class, and it's been quite awhile since I've used it. I was wondering if there was a way to allow spaces in a string (instead of it nulling out and ending the string)
my current code is this:
int chapter10() {
string strinput;
char charstr[1000];
int numwords=1;
cout << "Enter a phrase ";
cin >> strinput;
cout << strinput;
const int size = strinput.size() + 1;
strcpy_s(charstr, strinput.c_str());
cout << strinput << endl;
for (int i = 0; i != size; i++) {
if (*(charstr + i) == ' ')
numwords++;
}
cout << "There are " << numwords << " words in that string." << endl;
return 0;
}
The problem I'm having, is for instance, if I type "Hello World" and press enter, it pops the next line (right after the cin) and says "Hello", and the space made it cut the rest of the phrase off.
How does one fix this issue? I don't want to use the str:: things as I barely know what they are, and have really never had to use them, and that would look a bit suspicious to the teacher :P
Update: If you've suggested using getline(cin, strinput); It doesn't work too well. I can from what I see, only type in the 10 to reach my function, but after I press enter, it thinks that I've presses something else, which makes it completely skip the cin to get the string value. But, there is something weird with this, if I type "10 hello world" it does everything correctly. Well, with the exception that it needs to be in the same line as the number to reach the function.
Solved: The use of getline(cin, strinput) works perfectly fine, if you're not using user input before hand. If you are, you're going to need a cin.ignore before the getline(). As stated in the comment by my best answer.
#include <iostream>
#include <iomanip>
#include <string>
#include <limits>
using namespace std;
//~~~Initialize all functions
int chapter10();
//~~~Initializing complete
int main() {
srand(time(0)); //makes rng thingy work instead of choose same numbers cause it doesn't do it on its own. lol
cout << "Enter the chapter number you need to look at: ";
int chapterNumber;
cin >> chapterNumber;
switch (chapterNumber) {
case 1: testingStuff(); break;
case 9: chapter9(); break;
case 10: chapter10(); break;
default: cout << "You chose an invalid chapter number, reload the program."; break;
}
system("pause");//So console doesn't close instantly cause that's not annoying at all...
}
int chapter10() {
string strinput;
char charstr[10000];
int numwords=1;
cout << "Enter a phrase." << endl;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, strinput);
const int size = strinput.size() + 1;
strcpy_s(charstr, strinput.c_str());
for (int i = 0; i != size; i++) {
if (*(charstr + i) == ' ' & *(charstr + (i+1)) != ' ' )//the & is fail safe so multiple space no ++numwords
numwords++;
}
cout << "There are " << numwords << " words in that string." << endl;
return 0;
}
The way I have my code written was I used a switch/case to reach my function. This required user input, which in turn caused my program to 'think' I was still typing for the second input required in the chapter10 function.
Adding in the line of code: cin.ignore(numeric_limits<streamsize>::max(), '\n'); allowed me to cancel the input, and start a new one.
If you want to get all characters an end-user enters on a single line, use getline: instead of cin >> strinput write this:
getline(cin, strinput);
The fact that it is actually std::getline(std::cin, strinput) makes no difference, because your code uses std namespace anyway. In case you were wondering what std:: prefix is, it's a namespace of the Standard C++ library.
You can use getline() function
It copies into a string till a newline is reached or delimiter is found - so it will accept all the spaces till newline is reached
http://www.cplusplus.com/reference/string/string/getline/
or you can also use cin.getline() as shown here -
std::cin input with spaces?
use:
cin >> noskipws >> strinput;
Use std::getline() function. Example:
#include <iostream>
#include <vector>
#include <sstream>
void WordCounter(
const std::vector<std::string> & lines) {
for (int i = 0; i < lines.size(); ++i) {
std::istringstream iss(lines[i]);
std::string word;
int count = 0;
while (iss >> word) {
++count;
}
std::cout << "Line #" << i << " contains " << count << " words." <<
std::endl;
}
}
int main() {
std::string line;
std::vector<std::string> lines;
while (std::getline(std::cin, line)) {
lines.push_back(line);
}
WordCounter(lines);
return 0;
}
I want to ask for word from the user and then convert the word from string to char using 'strcpy'. Then I want to determine the sum of the ascii codes for all of the letters in the word.
However, I am having difficulties. I don't understand exactly how I can do that. This is what I have been able to do so far.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
string word;
cout << "Enter word: ";
getline(cin, word);
/*
char w[word];
strcpy(w,word.c_str());
int ('A');
cout<<char(65);
*/
return 0;
}
The commented part is where I have been trying to do the converting. I copied the code from a worksheet. Even if it did work, I don't know how, and what it all means.
Thanks for your help.
char w[word];
strcpy(w, word.c_str());
char w[word] is incorrect. The square brackets is for the size, which must be a constant integral expression. word is of type std::string, so this makes neither logical nor practical sense. Maybe you meant it as:
char w = word;
But that still won't work because word is a string, not a character. The correct code in this case is:
char* w = new char[word.size() + 1];
That is, you allocate the memory for w using a char*. Then you use word.size() + 1 to initialize heap-allocated memory amounting to those bytes. Don't forget for the obligatory delete[] when you're finished using w:
delete[] w;
However, note that using raw pointers and explicit new is not needed in this case. Your code can easily be cleaned up into the following:
#include <numeric>
int main ()
{
std::string word;
std::getline(std::cin, word);
int sum = std::accumulate(word.begin(), word.end(), 0); /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
std::cout << "The sum is: " << sum << std::endl;
}
You don't need to use strcpy() (or use a char * at all, for that matter), but this'll do your counting using a char pointer:
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
const char * cword = word.c_str();
int ascii_total = 0;
while ( *cword ) {
ascii_total += *cword++;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
Output:
paul#local:~/src/cpp/scratch$ ./asccount
Enter word: ABC
Sum of ASCII values of characters is: 198
paul#local:~/src/cpp/scratch$
If you really do want to use strcpy(), I'll leave it as an exercise to you to modify the above code.
Here's a better way to do it, just using std::string (and C++11, and obviously presuming your system uses the ASCII character set in the first place):
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
int ascii_total = 0;
for ( auto s : word ) {
ascii_total += s;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
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