For example, a user enters John as his name and i want to print just the first letter which is 'J'. How do we do that?
Thanks in advance..✌✌
Use std::cin to get name, and use operator [] to access character you want. First character has index 0. So first letter of name is name[0]
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cin >> name;
if (!name.empty())
{
std::cout << name[0];
}
}
Also check if string is not empty.
You can use std::string::at function
#include <iostream>
#include <string>
int main ()
{
std::string str ("Test string");
std::cout << str.at(0);
}
Related
Why this doesn't print the first word of sentence?
#include <iostream>
#include <string>
int main()
{
std::string sentence;
std::cout<<"Enter sentence: ";
std::cin>>sentence;
std::getline(std::cin,sentence);
std::cout<<sentence;
return 0;
}
If I enter
"This is text"
output would be
" is text"
You dont need the first cin (std::cin>>sentence;), this will solve your problem
#include <iostream>
#include <string>
int main()
{
std::string sentence;
std::cout<<"Enter sentence: ";
std::getline(std::cin,sentence);
std::cout<<sentence;
return 0;
}
std::cin>>sentence;
This line of code takes the first word you input.
Remove it and you are good to go
I am trying to write a program that will return words that start with the symbol # from a string.
For example:
A string such as "I like #tacos and #pizza" would return: #tacos #pizza
This is my current code:
int main(void){
string myString = "I like #tacos and #pizza";
std::istringstream iss(myString);
while(iss >> myString){
int i = 0;
if(myString[i] == '#'){
iss >> myString;
}
i++;
}
std::cout << myString;
}
However, this only returns one word that starts with a hashtag. Any help as to what I can change in the code?
You just need to check the string's first character with front or myString[0], and print the output in the loop. Your original code will at most print once so I move the print statement into the loop.
#include <iostream>
#include <sstream>
#include <string>
int main(void) {
std::string myString = "I like #tacos and #pizza";
std::istringstream iss(myString);
while (iss >> myString) {
if (myString.front() == '#') {
std::cout << myString << std::endl;
}
}
return 0;
}
Demo
I am working on a project where I have to parse data from user input.
#include <iostream> // for cin and cout
#include <iomanip> // for setw()
#include <cctype> // for toupper()
using namespace std;
int main(){
string playerInput;
cin >> playerInput;
//Player would input strings like C13,C 6, I1, Z 16, etc...
}
return 0;
I've tried something like this, which kinda works but only if the letter proceeds the number in the string.
int myNr = std::stoi(playerInput);
What my end goal is to grab the letter and number from the string, and place them in a char variable and a integer variable respectively. I am stuck on how to proceed from here and could use some help, thanks!
This is the simplest and the shortest way to achieve that (it also ignores spaces and tabs):
int main() {
char ch;
int n;
cin >> ch >> n;
cout << "ch = " << ch << ", n = " << n << endl;
}
I think that other answers are a bit overcomplicated.
You could do like what you had:
char letter = playerInput.front();
playerInput.erase(0);
int number = std::stoi(playerInput);
Of course, that doesn't allow for spaces. Removing spaces can be quite tedious, but it could be done like:
playerInput.erase(
std::remove_if(
begin(playerInput), end(playerInput),
[](uint8_t ch) { return std::isspace(ch); }),
end(playerInput));
Full Demo
Live On Coliru
#include <cctype> // for toupper()
#include <iomanip> // for setw()
#include <iostream> // for cin and cout
#include <algorithm> // for remove_if
static bool ignorable(uint8_t ch) {
return std::isspace(ch)
|| std::ispunct(ch);
}
int main() {
std::string playerInput;
while (getline(std::cin, playerInput)) {
playerInput.erase(
std::remove_if(
begin(playerInput), end(playerInput),
ignorable),
end(playerInput));
if (playerInput.empty())
continue;
char letter = playerInput.front();
playerInput.erase(begin(playerInput));
int number = std::stoi(playerInput);
std::cout << "Got: " << letter << " with " << number << "\n";
}
}
Prints
Got: C with 13
Got: C with 6
Got: I with 1
Got: Z with 16
You have the right idea in using std::stoi. My code expands your approach:
string playerInput;
getline(cin, playerInput);
char c1 = playerInput[0];
int num = stoi(playerInput.substr(1));
The above code receives an input string, then takes out the first character and uses std::stoi on the rest of the string.
Note that I use std::getline to account for the possibility of there being spaces in the input. If you are doing this repeatedly, you will need to add cin.ignore() after each getline() statement. See this link for more info.
std::cin stops reading input when it encounters a space. You can use std::getline() if your input has spaces. To parse your string, you should check out std::stringstream. It allows you to read from a string as if it were a stream like std::cin.
#include <iostream> // for cin and cout
#include <iomanip> // for setw()
#include <cctype> // for toupper()
#include <sstream>
int main(){
std::string playerInput;
int i;
char c;
std::getline(std::cin, playerInput); // Remove trailing newline
std::getline(std::cin, playerInput);
//Player would input strings like C13,C 6, I1, Z 16, etc...
//String Stream
std::stringstream playerInputStream(playerInput);
//Read as if you were reading through cin
playerInputStream >> c; //
playerInputStream >> i;
}
return 0;
I'm trying to make a program that will receive a string and output an uppercase version of that. My code works, however once it loops through the string and changes it, it immediately crashes and I'm not completely sure why. Here are my two pieces of code.
/*This program is to intended to receive a string and return a version of it in all upper case*/
#include <iostream>
#include <string>
#include <locale>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++;)
std::cout << std::toupper(str[i]); //A loop which goes through each digit of the string
break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
/*This program calls a function to make a string in upper case*/
#include <iostream>
#include <string>
#include <sstream>
#include <locale>
#include "toUpper1.h" //Calls the header file which contains the loop
using namespace std;
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
cout<<toUpper(input); //The command that causes the user input string to be transformed into upper case
return 0;
}
You can make string to uppercase using code bellow
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Or use like this
#include <algorithm>
#include <string>
std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
You are breaking the function without returning anything. Use {} to close for loops if you want to use break
prog.cpp:16:5: error: break statement not within loop or switch
break;
Also your for loop has an extra ; at the end.
std::cout and std::toupper are useless as you are already including namespace std;
and why are you using break;? there is no need of it.
just write
for (int i=0; i<str.length(); i++)
cout << toupper(str[i]);
Remove break;
You are not transforming the string, you are outputting its transformation in the function.
instead of
std::cout << std::toupper(str[i]);
use
str[i]=std::toupper(str[i]);
And move all printing out of the function. Changing the string doesn't include printing!
Notice the #bbdude95 answer, too.
edit
Instead of
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input;
use
char input[256];
cout << "Please type in a word:\n>";
cin.getline( input, 256, '\n' );
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string toUpper ( string str)
{
cout <<"\n"; //Puts spaces between the input and output
for (int i=0; i<str.length(); i++)
str[i] = std::toupper(str[i]); //A loop which goes through each digit of the string
//break;
cout <<"\n\n"; //Creates spaces after the output
return str;
}
int main ()
{
cout<<"\nPlease type in a word\n\n";
string input; //Creates a variable of cin that can be used in the toUpper command
cin>>input; //Makes a user input command part of the declared variable
//The command that causes the user input string to be transformed into uppe case
cout << toUpper(input);
cout << std::endl << "The original string is" << input << std::endl;
return 0;
}
EDIT: Note that keeping the function signature as above (string toUpper ( string str), as were required), we are making some extra string copies, and, most important: we are NOT modifying the original string (excute the code and see the result of last cout.
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