#include<iostream>
using namespace std;
int main()
{
string p;
int n,i;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>p;
cout<<p<<"\n";
}
return 0;
}
hiii..
i wanna take two strings and then print them one by one as in prog. but when i take n=2 and input the string "I wanna go"
it gives the output :
i
wanna
and it didn't ask me for second string.it is taking the string until it gets a whitespace.what should i do to resolve this?
You have to change the initial value of your iteration variable i in you for statement to the following one:
for(i=0;i<=n;i++)
Consider using std::getline.
std::string name;
std::getline(std::cin, name);
The above example is summarized from:
std::cin input with spaces?
Instead of operator >> you should use function std::getline. For example
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
std::cin.ignore( std::numeric_limits<std::streamsize>::max() );
// or simply std::cin.ignore();
for ( int i = 1; i <= n; i++ )
{
std::string p;
std::getline( std::cin, p );
std::cout << p << "\n";
}
return 0;
}
Related
I tried writing a string reversing program in C++. Though it seemed really simple, Idk why I ain't getting the correct output.
Here's my code:-
#include<iostream>
#include<string>
using namespace std;
string Reverse_string( string &s ){
for( size_t i{}; i<s.size() ; i++ ){
s.at(i)= s.at( s.size()-1-i );
}
return s;
}
int main(){
cout<<"Enter the string you want to reverse: ";
string s{};
getline(cin,s);
cout<<"\nThe reversed string is :"<< Reverse_string(s) << endl;
return 0;
}
Here is my output:-
Enter the string you want to reverse: string
The reversed string is :gniing
Please help me finding the bug!
In your code you are assigning the values s.at(i)= s.at( s.size()-1-i ); and thus it is changing the previous value of s.at(i), but you should swap the values of respective indexes, s.at(i) with s.at(s.size()-1-i). And also you only need to traverse the first half of the string to swap with respective last half of the string.
This works fine.
#include<iostream>
#include<string>
using namespace std;
string Reverse_string( string &s ){
for( size_t i{}; i<s.size()/2 ; i++ ){ // here you only need to go half
swap(s.at(i), s.at( s.size()-1-i )); // swap is builtin function
}
return s;
}
int main(){
cout<<"Enter the string you want to reverse: ";
string s{};
getline(cin,s);
cout<<"\nThe reversed string is :"<< Reverse_string(s) << endl;
return 0;
}
Instead of using functions. You can just use the headerfile #include <algorithm>. There is a built in reverse function.
#include <iostream>
#include <algorithm>
int main()
{
std::string s;
std::cout << "Enter the string you want to reverse: ";
std::cin >> s;
std::reverse(s.begin(), s.end());
std::cout << "The reversed string is: " << s;
return 0;
}
So guys, Actually What I wanna do here is that when I input 3,12,36 the output will be:
3
12
36
But here I have difficulty on how to make it output all the answer. What I have been doing is that when you input 3,12,36 it will output 3 12 only and if you type 3,12,36,48 it will output 3 12 36.
So it will always miss the last integer because my while loop is not correct I guess. but if I change it into
while(output >> life|| output >> ch)
It doesn't work either. I've done a lot of research but it still makes me confused and I'm still stuck on this part.
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life >> ch){
lifeishard.push_back(life);
//lifeishard.push_back(life2);
//lifeishard.push_back(life3);
}
return lifeishard;
}
int main() {
string str;
cin >> str;
vector<int> integers = parseInts(str);
for(int i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
return 0;
}
On your last number, the while loop fails because there's no character at the end. Just the end of the string. So it doesn't execute the push_back inside the loop.
Change it so that the while loop just gets the number. Then do the push_back in the loop. Then in the loop, after the push, get the comma character. Don't bother checking for failure getting the comma because when it goes around the while loop again it will fail and exit.
I changed to using getline in your main. I changed your loop index to size_t because it is never a good idea to mix signed and unsigned integers, and whenever you use a size() function, it's a size_t. When posting your program it really should include everything. My fixed up version of your program:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
vector<int> parseInts(string str) {//23,4,56
vector<int>lifeishard;
stringstream output;
string lifeisgood = str;
output.str(lifeisgood);
int life;
char ch;
while(output >> life){
lifeishard.push_back(life);
output >> ch;
}
return lifeishard;
}
int main() {
string str;
getline(cin, str);
vector<int> integers = parseInts(str);
for(size_t i = 0; i < integers.size(); i++) {
cout << integers[i] << "\n";
}
// Here is how we do for loops over containers in modern C++
for(auto x: integers) {
cout << x << '\n';
}
return 0;
}
A combination of stringstream, getline with delimiter and stoi would be enough for the conversion:
From the C++ reference for getline with delimiter:
Extracts characters from is and stores them into str until the delimitation character delim is found.
With this in mind, the code example below assumes the input is well-formed:
Example
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
vector<int> parseInts(const string& str, const char delim = ',')
{
vector<int> parsed;
stringstream ss(str);
string s;
while (getline(ss, s, delim)) // <- stores input in s upon hitting delimiter
parsed.push_back(stoi(s)); // <-- convert string to int and add it to parsed
return parsed;
}
int main()
{
string str = "3,12,36"; // <-- change to cin if you'd like
vector<int> ints = parseInts(str);
for (auto& i : ints)
cout << i << "\n";
}
Output
3
12
36
See more: getline, stoi
I'm writing a program that prompts the user for:
Size of array
Values to be put into the array
First part is fine, I create a dynamically allocated array (required) and make it the size the user wants.
I'm stuck on the next part. The user is expected to enter in a series of ints separated by commas such as: 1,2,3,4,5
How do I take in those ints and put them into my dynamically allocated array? I read that by default cin takes in integers separated by whitespace, can I change this to commas?
Please explain in the simplest manner possible, I am a beginner to programming (sorry!)
EDIT: TY so much for all the answers. Problem is we haven't covered vectors...is there a method only using the dynamically allocated array I have?
so far my function looks like this. I made a default array in main. I plan to pass it to this function, make the new array, fill it, and update the pointer to point to the new array.
int *fill (int *&array, int *limit) {
cout << "What is the desired array size?: ";
while ( !(cin >> *limit) || *limit < 0 ) {
cout << " Invalid entry. Please enter a positive integer: ";
cin.clear();
cin.ignore (1000, 10);
}
int *newarr;
newarr = new int[*limit]
//I'm stuck here
}
All of the existing answers are excellent, but all are specific to your particular task. Ergo, I wrote a general touch of code that allows input of comma separated values in a standard way:
template<class T, char sep=','>
struct comma_sep { //type used for temporary input
T t; //where data is temporarily read to
operator const T&() const {return t;} //acts like an int in most cases
};
template<class T, char sep>
std::istream& operator>>(std::istream& in, comma_sep<T,sep>& t)
{
if (!(in >> t.t)) //if we failed to read the int
return in; //return failure state
if (in.peek()==sep) //if next character is a comma
in.ignore(); //extract it from the stream and we're done
else //if the next character is anything else
in.clear(); //clear the EOF state, read was successful
return in; //return
}
Sample usage http://coliru.stacked-crooked.com/a/a345232cd5381bd2:
typedef std::istream_iterator<comma_sep<int>> istrit; //iterators from the stream
std::vector<int> vec{istrit(in), istrit()}; //construct the vector from two iterators
Since you're a beginner, this code might be too much for you now, but I figured I'd post this for completeness.
A priori, you should want to check that the comma is there, and
declare an error if it's not. For this reason, I'd handle the
first number separately:
std::vector<int> dest;
int value;
std::cin >> value;
if ( std::cin ) {
dest.push_back( value );
char separator;
while ( std::cin >> separator >> value && separator == ',' ) {
dest.push_back( value );
}
}
if ( !std::cin.eof() ) {
std::cerr << "format error in input" << std::endl;
}
Note that you don't have to ask for the size first. The array
(std::vector) will automatically extend itself as much as
needed, provided the memory is available.
Finally: in a real life example, you'd probably want to read
line by line, in order to output a line number in case of
a format error, and to recover from such an error and continue.
This is a bit more complicated, especially if you want to be
able to accept the separator before or after the newline
character.
You can use getline() method as below:
#include <vector>
#include <string>
#include <sstream>
int main()
{
std::string input_str;
std::vector<int> vect;
std::getline( std::cin, input_str );
std::stringstream ss(str);
int i;
while (ss >> i)
{
vect.push_back(i);
if (ss.peek() == ',')
ss.ignore();
}
}
The code is taken and processed from this answer.
Victor's answer works but does more than is necessary. You can just directly call ignore() on cin to skip the commas in the input stream.
What this code does is read in an integer for the size of the input array, reserve space in a vector of ints for that number of elements, then loop up to the number of elements specified alternately reading an integer from standard input and skipping separating commas (the call to cin.ignore()). Once it has read the requested number of elements, it prints them out and exits.
#include <iostream>
#include <iterator>
#include <limits>
#include <vector>
using namespace std;
int main() {
vector<int> vals;
int i;
cin >> i;
vals.reserve(i);
for (size_t j = 0; j != vals.capacity(); ++j) {
cin >> i;
vals.push_back(i);
cin.ignore(numeric_limits<streamsize>::max(), ',');
}
copy(begin(vals), end(vals), ostream_iterator<int>(cout, ", "));
cout << endl;
}
#include <iostream>
using namespace std;
int main() {
int x,i=0;
char y; //to store commas
int arr[50];
while(!cin.eof()){
cin>>x>>y;
arr[i]=x;
i++;
}
for(int j=0;j<i;j++)
cout<<arr[j]; //array contains only the integer part
return 0;
}
The code can be simplified a bit with new std::stoi function in C+11. It takes care of spaces in the input when converting and throws an exception only when a particular token has started with non-numeric character. This code will thus accept input
" 12de, 32, 34 45, 45 , 23xp,"
easily but reject
" de12, 32, 34 45, 45 , 23xp,"
One problem is still there as you can see that in first case it will display " 12, 32, 34, 45, 23, " at the end where it has truncated "34 45" to 34. A special case may be added to handle this as error or ignore white space in the middle of token.
wchar_t in;
std::wstring seq;
std::vector<int> input;
std::wcout << L"Enter values : ";
while (std::wcin >> std::noskipws >> in)
{
if (L'\n' == in || (L',' == in))
{
if (!seq.empty()){
try{
input.push_back(std::stoi(seq));
}catch (std::exception e){
std::wcout << L"Bad input" << std::endl;
}
seq.clear();
}
if (L'\n' == in) break;
else continue;
}
seq.push_back(in);
}
std::wcout << L"Values entered : ";
std::copy(begin(input), end(input), std::ostream_iterator<int, wchar_t>(std::wcout, L", "));
std::cout << std::endl;
#include<bits/stdc++.h>
using namespace std;
int a[1000];
int main(){
string s;
cin>>s;
int i=0;
istringstream d(s);
string b;
while(getline(d,b,',')){
a[i]= stoi(b);
i++;
}
for(int j=0;j<i;j++){
cout<<a[j]<<" ";
}
}
This code works nicely for C++ 11 onwards, its simple and i have used stringstreams and the getline and stoi functions
You can use scanf instead of cin and put comma beside data type symbol
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a[10],sum=0;
cout<<"enter five numbers";
for(int i=0;i<3;i++){
scanf("%d,",&a[i]);
sum=sum+a[i];
}
cout<<sum;
}
First, take the input as a string, then parse the string and store it in a vector, you will get your integers.
vector<int> v;
string str;
cin >> str;
stringstream ss(str);
for(int i;ss>>i;){
v.push_back(i);
if(ss.peek() == ','){
ss.ignore();
}
}
for(auto &i:v){
cout << i << " ";
}
I have an input file that contains some data in coordinate mode
For example (2,3,5) translates to column 2, row 3, and level 5. I'm curious on a method of reading in the numbers after using getline(cin,string) to obtain the data. I don't know how many digits are in the data points so i can't assume the 1st character will be of length 1. Is there any libraries that can help solve the problem faster?
my gameplan so far that's not finished
void findNum(string *s){
int i;
int beginning =0;
bool foundBegin=0;
int end=0;
bool foundEnd=0
while(*s){
if(isNum(s)){//function that returns true if its a digit
if(!foundBegin){
foundBegin=1;
beginning=i;
}
}
if(foundBegin==1){
end=i;
foundBegin=0;
}
i++;
}
}
Try this:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <vector>
#include <string>
int main() {
std::vector <std::string> params;
std::string str;
std::cout << "Enter the parameter string: " << std::endl;
std::getline(cin, str);//use getline instead of cin here because you want to capture all the input which may or may not be whitespace delimited.
std::istringstream iss(str);
std::string temp;
while (std::getline(iss, temp, ',')) {
params.push_back(temp);
}
for (std::vector<std::string>::const_iterator it=params.begin(); it != params.end(); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
The only caveat is that the arguments will have to be non whitespace delimited.
Example input string:
1,2,3
Output:
1
2
3
Once these arguments have been parsed, you can then convert them from strings to (example) integer via the following:
template <typename T>
T convertToType(const std::string &stringType) {
std::stringstream iss(stringType);
T rtn;
return iss >> rtn ? rtn : 0;
}
which can be used as follows:
int result = convertToType<int>("1");//which will assign result to a value of 1.
UPDATE:
This now works correctly on whitespace delimited input (except for newlines) like the following:
1 , 2, 3 , 4
Which yields:
1
2
3
4
jrd1's answer is pretty good, but if you'd prefer there happen to be functions for converting characters to integers (and back) already in the C standard library (cstdlib). You'd be looking for atoi.
http://en.cppreference.com/w/cpp/string/byte/atoi
#include <sstream>
void findNums(const string &str, int &i, int &j, int &k)
{
std::stringstream ss(str);
char c;
ss >> c >> i >> c >> j >> c >> k;
}
Simply use extractor operator for reading any type of value in respective variable type.
#incude<ifstream> // for reading from file
#include<iostream>
using namespace std;
int main()
{
int number;
ifstream fin ("YouFileName", std::ifstream::in);
fin >> number; // put next INT no matter how much digit it have in number
while(!fin.eof())
{
cout << number << endl;
fin >> number; // put next INT no matter how much digit it have in number and it will ignore all non-numeric characters between two numbers as well.
}
fin.close();
return 0;
}
Have a look over here for more details.
Note: Be careful while using it for character arrays and strings.. :)
I want to declare two types of variables in for's init-statement. like the following codes. I know "for (string word, int numb, ; cin>>word>>numb; )" is not working. just trying to let you know what I am trying to do. My goal is to declare two types of variables with the same lifetime and cin them together. Other way of coding is helpful too. thanks in advance.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
cout<<"enter a word and a number"<<endl;
for (string word, int numb, ; cin>>word>>numb; )
{
//do some work
}
return 0;
}
ok, I think this is the closest I can get as someone suggested.
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main ()
{
vector<pair<string,int> > pvec;
cout<<"enter a word and a number"<<endl;
{
int numb=0;
for (string word; cin>>word>>numb; )
pvec.push_back(make_pair(word,numb));
}
cout<<pvec[3].second<<endl;
return 0;
}
About the nearest you can get is:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
for (int numb; cin>>word>>numb; )
{
//do some work
}
}
return 0;
}
The extra set of braces limits the scope of word similarly to the way the loop limits the scope of numb. Clearly, you could reverse the declarations; it might be better (more symmetric) to use:
int main ()
{
cout<<"enter a word and a number"<<endl;
{
string word;
int numb;
while (cin>>word>>numb)
{
//do some work
}
}
return 0;
}
Since there is no increment or initialize operation, the code is really a while loop with a couple of declared variables; this achieves the same result and works.
This is not possible. You can declare two variables of the same basic type in the initialization statement in the for loop, but you cannot declare two variables of different basic types. You have to declare one outside of the for loop.
I'm fairly certain it's not possible to declare 2 variables of 2 different types in a for statement, but I also fail to see the advantage to doing so over something like this:
int main ()
{
cout<<"enter a word and a number"<<endl;
while( cin.good() )
{
string word;
int num;
cin >> word >> num;
//do some work
}
return 0;
}
In general I prefer to use for loops where there is something to count or at least iterate over. Other situations should be using a while or do loop.
The way you are trying to do it is not the cleanest way. I'd do it like this:
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
word and num are in the same scope (same "lifetime")
Note that you'd want to substitute the while(true) with some suitable condition.
If you want word and num to be inside the scope of the loop do something like:
while(true)
{
string word;
int num;
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
OR
{
string word;
int num;
while(true)
{
cin >> word >> num;
if (!cin.good()) break;
// do some work
}
}
I don't know why this would be necessary though.
The following is untested, but should work:
int main()
{
std::cout << "enter a word and a number" << endl;
for (struct { std::string word, int number } vars;
std::cin >> vars.word >> vars.number;
)
{
//do some work
}
return 0;
}
Since c++17:
#include <iostream>
#include <tuple>
int main() {
for (auto && [w,i] = std::tuple{std::string{},int{}} ; std::cin >> w >> i ; )
std::cout << "word " << w << " number " << i << "\n";
return 0;
}