Changing string to capital letters function - c++

I'm dealing with some excercise, according to which I have to change string given on the input to the same string, written with capital letters.
Here's is my try, for some strange reason it prints out only the first word of string, it doesn't read the bit that is after space...
Any ideas how to fix it ?
#include <iostream>
#include <string>
using namespace std;
void uppercase(string str)
{
locale loc;
for(size_t i=0; i<str.length(); ++i)
{
cout << toupper(str[i], loc);
}
}
int main(void)
{
string text;
cout << "Input text, please: " << endl;
cin >> text;
uppercase(text);
}
I know that there might be different ways to solve this excersice, but I would like to stick with my method. Any potential mistakes ?

Sure, use std::getline to get a whole line instead of one word. You should almost always use it, actually, because line-oriented is the way most programs take input.

Reading from std::cin is space-delimited. In order to get the whole string up to a new-line, you want std::getline.
std::getline( std::cin, text);

void uppercase(string str)
{
locale loc;
for(size_t i=0; i<str.length(); ++i)
{
if(str[i] != " ")
{
cout << toupper(str[i], loc);
}
}
}

Related

C++ User defined string needs to contain spaces (but not allowed by program..?)

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;
}

How can I get the number of characters from an input string?

I am trying to count the number of characters in a string that is provided by the user. I know I can use string::length() and string::size() but when a space is encountered, the count is stopped. For example, say the user inputs "Bob Builder", the count should be 10 but what my code would display would be 3. Also I am trying to do this without using a character array. Any suggestions? An explanation would also greatly help.
int main()
{
string Name;
cin>>Name;
cout << name(Name);
return 0;
}
int name(string a)
{
int numChar;
/*for (int i=0; a[i] != '\0';i++)
{
if (!isspace(a[i]))
numChar++;
}*/
numChar=a.length();
return numChar;
}
How yu know when input is over?
If you want to read until end of line then this is a possible solution:
std::string line ;
std::cin.getline(line) ;
line.length() ;
You have to use getline() instead of cin to get all line up to newline. cin reads input up to whitespace.
std::getline (std::cin,Name);
If you use using namespace std;
getline (cin,Name);
If you want to count the input string excluding spaces, the code snippet helps you.
#include <algorithm>
#include <string>
int main()
{
std::string s = "Hello there, world!";
std::cout << std::count( s.begin(), s.end(), ' ' ) << std::endl;
}

How to convert a sentence from upper case to lower case that contains space and numbers

I'm trying to convert a sentence from upper case to lowercase. I also write a code but I stopper when a space is appear. How can I fix this problem and convert the whole sentence? Here is my code
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[100];
cin>>str;
for(int i=0;i<strlen(str);i++)
{
if(str[i]>='A'&&str[i]<='Z')
{
str[i]=str[i]+32;
}
}
cout<<str<<endl;
return 0;
}
It's because of theinput operator >>, it breaks on space. If you want to read a whole line then use std::getline to read into a std::string instead.
Then read about the C++ standard algorithms, like for example std::transform. Also, std::tolower doesn't modify anything that's not an upper-case letter, so it's a good function to use.
The error is because operator>> delimites on spaces. The alternative is to use getline. See the following example:
#include <cstring>
#include <iostream>
#include <string>
int main() {
std::string s;
std::getline(std::cin, s);
std::cout << "Original string: " << s << std::endl;
if (!std::cin.fail()) {
const int len = strlen(s.c_str());
for (size_t i = 0; len > i; ++i) {
if ((s[i] >= 'A') && (s[i] <= 'Z'))
s[i] = s[i] - 'A' + 'a';
}
}
std::cout << "New string: " << s << std::endl;
return 0;
}
The reason input stops at whitespace is because formatted input is delimited by whitespace characters (among others). You will need unformatted I/O in order to extract the entire string into str. One way to do this is to use std::istream::getline:
std::cin.getline(str, 100, '\n');
It's also useful to check if the input succeeded by using gcount:
if (std::cin.getline(str, 100, '\n') && std::cin.gcount())
{
...
}
But in practice it's recommended that you use the standard string object std::string which holds a dynamic buffer. To extract the entire input you use std::getline:
std::string str;
if (std::getline(std::cin, str)
{
...
}
Here is one of the examples of doing it using transform function.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str;
if (getline(cin, str))
{
transform(str.begin(), str.end(), str.begin(), ptr_fun<int, int>(toupper));
}
cout << str << endl;
return 0;
}

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;
}

Testing for a space character inside a string...?

I'm trying to test if a character in a string is a space, and I'm getting extremely frustrated:
string my_string;
cin >> my_string;
for (int i = 0; i < my_string.length(); i++)
{
if (my_string[i] == ' ') // this never becomes true...
{
cout << "this text should pop, but never does" << endl;
}
}
I'm not getting any errors and I've looked online, but people on different forums say this is how to test for a space. Uh.
when you say
cin >> my_string;
you are taking formatted input. std::cin discards any whitespace in that line, and it reads up to and yields only a single word.
try instead
std::string my_string;
std::getline(std::cin, my_string);
to get a single line, or
#include <iterator>
// ...
std::string my_string((std::istreambuf_iterator<char>(std::cin)),
std::istreambuf_iterator<char>());
to get everything up to an end-of-file mark into the string.
Thats because cin stops reading at the first whitespace so you never actually read the entire sentence but the first word. Use getline instead.
std::string my_string;
std::getline(std::cin, my_string);
for (int i = 0; i < my_string.length(); i++)
{
if (my_string[i] == ' ') // this never becomes true...
{
std::cout << "this text should pop, but never does" << std::endl;
}
}
Additionnally to test whether a space is present use std::string::find!
std::string my_string;
std::cin >> my_string; // please do not use « using namespace std; » if possible
size_t space_position = my_string.find(' ');
if(space_position != std::string::npos)
{
std::cout << "found space" << std::endl;
}