C++ String input in Vector [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 1 year ago.
I want to input multi-word strings into vector "name". Using cin works fine for single word inputs.
What i want is :
Take number of string inputs from the user. for example : "Random Name"
Store all the String value into the vector names
Here is the code i wrote
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> names;
string user;
int n;
cout << "Enter number of Users : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> user;
names.push_back(user);
}
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << " ";
}
}
Problem:
When i use getline() instead of cin in the for loop, it omits 1 input.
For example , if the user inputs - Number of Users = 3, it only takes 2 string inputs
string user[n]; // value of n given by user using cin
for (int i = 0; i < n; i++)
{
getline(cin, user[i]);
names.push_back(user[i]);
}

Try this:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> names;
string user;
int n;
cout << "Enter number of Users : ";
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> std::ws;
getline(cin,user);
names.push_back(user);
}
for (int i = 0; i < names.size(); i++)
{
cout << names[i] << " ";
}
}
cin>>std::ws;
The issue here is that the compiler is considering the newline after you are entering the number of inputs, and pressing enter. So, the fix is to extract the additional whitespaces. Check http://www.cplusplus.com/reference/istream/ws/

Related

C++ Program Returning Abort Trap

I'm trying to write a C++ that inputs n and then inputs n words. Then I input an s and then print out the n words with s removed. When I try to implement my program, my program says that there is an abort error. Does anyone know why? Thanks a lot.
#include <iostream>
using namespace std;
int main() {
int n;
string words[100];
cin >> n;
for (int i=0; i<n; i++) {
cin >> words[i];
}
string s; cin >> s;
for (int i=0; i<n; i++) {
int n = words[i].find(s);
words[i] = words[i].erase(n,n+s.length());
}
for (int i=0; i<n; i++) {
cout << words[i] << endl;
}
}

Comparing an element of a string array with a string

So, while practicing strings i came across this question that gave me, "n" number of strings and it asked me to output strings in increasing alphabetical order.
Example :
Input>>
4 // number of string
abcdef ghi // string 1
ccdef // string 2
bcdcas // string 3
xcxvb // string 4
vxzxz // string 5
This will output only strings 1,2,4 because we have to print string in an increasing alphabetical way.
string 1 < string 2 < string 4.
(string 3 is smaller than string 2, and hence the output)
So i coded the problem without using string array and it worked, but when i applied the same approach the output was not correct.
Maybe i don't know something about string array that you guys can help me with.
Here is the code for you guys :
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string array[n];
cin.ignore();
for(int i=0; i<n;i++){
getline(cin , array[i]);
}
cout << array[0] << endl;
string maximum;
for(int i = 0; i<n; i++){
maximum = array[0];
if(array[i] > maximum){
maximum = array[i];
cout << maximum << endl;
}
}
}
Here is the code that worked without any problems:
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string text;
cin.ignore();
string max = "";
for(int i=0; i<n;i++){
getline(cin , text);
if(text>max){
max = text;
cout << text << endl;
}
}
}
I've used your working code as a starting point. Try to avoid c-style arrays and use one of the C++ containers (like std::vector) instead.
#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
std::string text;
std::vector<std::string> array;
std::cout << "Enter number of strings: ";
std::cin >> n;
std::cin.ignore();
for(int i=1; i<=n;i++) {
std::cout << "Enter string " << i << ": ";
std::getline(std::cin, text);
// check if we already have stored anything in the array and
// then check if text is <= than the last element in the array.
// if so, continue will skip to the next iteration in the for-loop
if(array.size()>0 && text<=array.back()) continue;
std::cout << "saved " << text << "\n";
array.emplace_back(std::move(text));
}
std::cout << "All saved strings:\n";
for(auto& s : array) {
std::cout << s << "\n";
}
}

c++: how to use char / string 2d array to accept more than 1 sentense from an user?

Below code failed:
#include <iostream>
#include <string>
using namespace std;
int main(){
int a, b;
cout << "how many input you want to give ? ";
cin >> a;
b = a - 1;
string str[b];
for(int i = 0; i <= b; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < a; k++){
cout << "You entered: " << str[k] << endl;
}
return 0;
}
But if I fix the value of 'int a' then the code is running. please help.
Arrays must have a constant size at compile-time so to create an array with dynamic size you can create it on the heap using keyword new and delete[] to free up memory.
Also what is the point in:
cin >> a;
b = a - 1; //?
You can easily do it like this:
int n;
cout << "how many input you want to give ? ";
cin >> n;
string* str = new string[n];
for(int i = 0; i < n; i++){
cout << "Enter a string: ";
getline(cin, str[i]);
}
for(int k = 0; k < n; k++){
cout << "You entered: " << str[k] << endl;
}
Don't forget to clean when you're done:
delete[] str;
You'll want to clear the input buffer, the newline from "How many input you want to give ?" is being fed into the first "Enter a string:".
Add this line after cin>>a;
cin.ignore(INT_MAX, '\n');
Use a vector to store the input.
#include <vector>
#include <string>
#include <iostream>
using names pace std;
int main ()
{
vector <string> input;
string tmp;
while (getline(cin, tmp))
input.push_back(tmp));
for(auto s : input)
cout << s << '\n';
}

Unexpected cin behavior

I am writing a function int count_words(string str) that returns a count of all of the words in the string.
The issue is that regardless of the input, the result is 1. Can anyone help?
#include <iostream>
#include <string>
using namespace std;
int count_words(string str)
{
int i,j;
j = 1;
int l = str.length();
for(i = 0; i < l; i++)
{
string c = str.substr(i,1);
if(c == " ")
{
j++;
}
}
cout << "The total word in the string: " << j << endl;
return j;
}
int main()
{
string str;
cout << "Please enter a string: ";
cin >> str;
int result = count_words(str);
return 0;
}
You should use cin.getline if your string contains spaces, as using the >> operator with cin only reads up to the next whitespace
See std::cin input with spaces?
Consider iterating over the string:
auto cstyle= str.c_str();
for (int i = 0; i < str.length(); ++i)
{
if (cstyle[i]==' ')//assumes words are delimited by a single space
{
j++;
}
}
You should use: cin.getline, for example:
int main()
{
cout << "Please enter a string: ";
unsigned size=10;
char*chr=new char[size];
cin.getline(chr,size);
string str(chr);
//cin >> str;
int result = count_words(str);
return 0;
}

Read line of numbers from stdin [duplicate]

This question already has answers here:
How to determine if a string is a number with C++?
(36 answers)
Closed 8 years ago.
I am working on program that would calculate with matrixes but i am not sure what is best way how to read matrix line by line from command line.
My goal is this:
Please enter number of lines:
2
Please enter line 1/2:
1 4 5 2
Please enter line 2/2:
1 5 7 8
At the end of this i would like to have array or vector of numbers 1,4,5,2,1,5,7,8.
This is my code:
vector<string>matrix;
string input;
int nrows;
cout << "Enter number of rows:" << endl;
cin >> nrows;
getline(cin, input);
for (int i = 1; i <= nrows; i++) {
cout << "Enter line " << i << "/" << nrows << endl;
getline(cin, input);
matrix.push_back(input);
}
for (int i = 0; i < matrix.size();i++){
cout << matrix.at(i)<<endl;
}
This reads whole line and save it into vector of string and there is much to do to separate just numbers. Is there any way how could I load only numbers in the line ? So for example for the line:
1 a 3 2 4sdsd
I would get numbers 1,3,2,4 ?
Thank for any help.
string process(const string& input) // Removes all characters except <space> and digits [0-9]
{
string ret;
for(int i=0; i<(int)input.size(); i++)
{
if(input[i]==' '||(input[i]>='0'&&input[i]<='9'))
ret+=input[i];
}
return ret;
}
int main()
{
int nrows;
string input;
cout<<"Enter number of rows - ";
cin>>nrows;
cin.get(); // Take the remaining <Enter>
vector<vector<int> > matrix(nrows); // A 2-D vector representing the matrix
for(int i=0; i<(int)matrix.size(); i++)
{
cout<<"Please enter line "<<i+1<<"/"<<nrows<<" -: \n";
getline(cin,input);
stringstream ss(process(input));
int num;
while(ss>>num)
{
matrix[i].push_back(num);
}
}
for(int i=0; i<(int)matrix.size(); i++) // Display the matrix
{
for(int j=0; j<(int)matrix[i].size(); j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<"\n";
}
}
I would use a 2D vector. Also, ask the user for number of columns:
vector<vector<int>> matrix;
int nrows, ncols;
cout << "Enter number of rows:" << endl;
cin >> nrows;
cout << "Enter number of columns:" << endl;
cin >> ncols;
matrix.resize(nrows);
for (int i = 0; i < nrows; i++) {
cout << "Enter line " << (i+1) << "/" << nrows << endl;
int tmp;
while (matrix[i].size() < ncols) {
while (!(cin >> tmp)) { // Not a number. Clear cin
cin.clear();
cin.ignore(1);
}
matrix[i].push_back(tmp);
}
}
One way to do it:
// only allow digits and spaces
string removeNonNumbers(const string& s) {
stringstream ss;
for(int i=0; i<s.length(); ++i) {
if(isdigit(s[i]) || ' ' == s[i])
ss << s[i];
}
return ss.str();
}
vector<int> splitToInts(const string& s) {
vector<int> ret;
stringstream ssin(s);
while (ssin.good()){
string tmp;
ssin >> tmp;
ret.push_back(atoi(tmp.c_str()));
}
return ret;
}
To use it, do this when reading input in your getline loop:
vector<int> numbers = splitToInts( removeNonNumbers(input) );