string fruits[200];
How can I input a string into the array ?
Example:
My mom has apples;
So , fruits array will contain:
fruits[0] = "My";
fruits[1] = "mom";
..........etc.
How can I do that?
If you're reading from the standard input:
int i = 0;
for (string word; cin >> word; i++)
names[i] = word;
If you're reading from a string, use istringstream instead.
If you would like to use the standard C++ library to its fullest, use input iterators and a vector<string> instead of an array:
vector<string> words;
back_insert_iterator< vector<string> > back_iter (words);
istream_iterator<string> eos;
istream_iterator<string> iit (cin);
copy (iit, eos, back_iter);
Using vector<string> fixes the problem of having to guess how many words would be entered, and living with the consequences of making a wrong guess.
The most compact solution:
vector<string> words;
copy(istream_iterator<string>(cin),
istream_iterator<string>(),
back_inserter(words));
This is #dasblinkenlight's solution, written using temporary variables.
Related
My input file userinfo.csv contains username and password in this format username,password shown below.
frierodablerbyo,Rey4gLmhM
pinkyandluluxo,7$J#XKu[
lifeincolorft,cmps9ufe
spirginti8z,95tcvbku
I want to store all the usernames and passwords in
vector<string> usernames;
vector<string> passwords;
I've never used C++ for file handling, only python
EDIT1
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream myfile;
myfile.open("small.csv");
vector<string> data;
vector<string> usernames, passwords;
while(myfile.good()){
string word;
getline(myfile, word, ',');
data.push_back(word);
}
for(int i=0; i<8; i=i+2){
usernames.push_back(data[i]);
}
for(int i=1; i<8; i=i+2){
passwords.push_back(data[i]);
}
}
I know above code is bad, how can I improve it because my actual csv file contains 20000 rows.
The code snipplet already posted is fine, but keep in mind that the CSV separators are locale-dependent, e. g. for US its a ',', for Germany it would be ';' and so on. Also if you have text sections in your CSV which might contain one of those characters, you have to check for opening and closing quotation marks.
The most easy thing to do is to use a ready-made library for parsing CSVs, for example https://github.com/d99kris/rapidcsv.
You can try something like this
std::vector <std::pair<std::string, std::string>> vec_credentials;
std::ifstream is("credentials.csv");
if(is.is_open())
{
std::string line;
while(getline(is, line))
{
std::stringstream ss(line);
std::string token;
std::vector <std::string> temp;
// this is good if in the future you will have more than 2 columns
while(getline(ss, token, ','))
{
temp.push_back(token);
}
vec_credentials.push_back(std::make_pair(temp[0], temp[1]));
}
is.close();
}
Recently I faced a problem
But before that I will tell you what is the reference
Consider this program
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> RS;
string word;
while(cin>>word)
RS.push_back(word);
}
This code stores each word of spaced string in vector
But the problem comes here .....
#include<bits/stdc++.h>
using namespace std;
int main()
{
vector<string> RS,FS;
string word;
while(cin>>word)
RS.push_back(word);
while(cin>>word)
FS.push_back(word);
}
Here the motive is to store the string words of first line in RS
and of second line in FS vectors
But it doesn't stop at the end of one line and store all words in RS
and FS remains empty.
Please Suggest a way to do the same program correctly
or
If you know more efficient way you are more than Welcome
Thanks in Advance
Use getline and istringstream, separately for each sentence, and then push_back each word in them:
string line;
getline(cin, line); //Get sentence 1
istringstream iss1(line);
while ( iss1 >> word) {
RS.push_back(word);
}
getline(cin, line); //Get sentence 2
istringstream iss2(line);
while ( iss2 >> word) {
FS.push_back(word);
}
The newline character ('\n') acts as the delimiting character for getline().
I have an input getline:
man,meal,moon;fat,food,feel;cat,coat,cook;love,leg,lunch
And I want to split this into an array when it sees a ;, it can store all values before the ; in an array.
For example:
array[0]=man,meal,moon
array[1]=fat,food,feel
And so on...
How can I do it? I tried many times but I failed!😒
Can anyone help?
Thanks in advance.
You can use std::stringstream and std::getline.
I also suggest that you use std::vector as it's resizeable.
In the example below, we get input line and store it into a std::string, then we create a std::stringstream to hold that data. And you can use std::getline with ; as delimiter to store the string data between the semicolon into the variable word as seen below, each "word" which is pushed back into a vector:
int main()
{
string line;
string word;
getline(cin, line);
stringstream ss(line);
vector<string> vec;
while (getline(ss, word, ';')) {
vec.emplace_back(word);
}
for (auto i : vec) // Use regular for loop if you can't use c++11/14
cout << i << '\n';
Alternatively, if you can't use std::vector:
string arr[256];
int count = 0;
while (getline(ss, word, ';') && count < 256) {
arr[count++] = word;
}
Live demo
Outputs:
man,meal,moon
fat,food,feel
cat,coat,cook
love,leg,lunch
I don't want to give you some code because you must be new at C++ and you have to learn by yourself but I can give an hint: use substring to store it into a vector of string.
I want to read just the first line of standard input, and place the the values into a vector (unknown number of entries). With each vector element holding a value (i.e. vector[1]=1, vector[2]=-30...)
E.g.
1 -30 10 300
I've tried just using a while loop and cin, but I can't seem to make it stop at the terminating character /n. And I've been trying to implement this with getline, but I'm having no luck. Is there a good method to store integers from standard input, into a vector?
Any help is appreciated,
Thank you in advance. :)
std::string line;
if( std::getline(std::cin, line) ) {
std::istringstream ss(line);
int i;
while(ss >> i) {
vec.push_back(i);
}
}
As an alternative you can also use istream iterators on ss.
The below code works fine for your problem. the answer from Mohit should use getline not readline
vector <int> vec;
string input;
getline(cin,input);
istringstream ss(input);
int num;
while (ss >> num)
{
vec.push_back(num);
}
vector<int>::iterator itr = vec.begin();
while (itr != vec.end())
{
cout << *itr << endl;
itr++;
}
The snippet prints back to the standard output.
Why you are not able to stop using cin is it ignores white-space and end of line \n.
I have a program that need to get multiple cstrings. I current get one at a time and then ask if you want to input another word. I cannot find any simple way to get just one input with words divided be whitespace. i.e. "one two three" and save the the input in an array of cstrings.
typedef char cstring[20]; cstring myWords[50];
At the moment I am trying to use getline and save the input to a cstring and then I am trying to use the string.h library to manipulate it. Is that the right approach? How else could this be done?
If you really have to use c-style strings, you could use istream::getline, strtok and strcpy functions:
typedef char cstring[20]; // are you sure that 20 chars will be enough?
cstring myWords[50];
char line[2048]; // what's the max length of line?
std::cin.getline(line, 2048);
int i = 0;
char* nextWord = strtok(line, " \t\r\n");
while (nextWord != NULL)
{
strcpy(myWords[i++], nextWord);
nextWord = strtok(NULL, " \t\r\n");
}
But much better would be to use std::string, std::getline, std::istringstream and >> operator instead:
using namespace std;
vector<string> myWords;
string line;
if (getline(cin, line))
{
istringstream is(line);
string word;
while (is >> word)
myWords.push_back(word);
}
std::vector<std::string> strings;
for (int i = 0; i < MAX_STRINGS && !cin.eof(); i++) {
std::string str;
std::cin >> str;
if (str.size())
strings.push_back(str);
}