Can you use "cin" with string? - c++

I was taught that you have to use gets(str) to input a string and not cin. However I can use cin just fine in the program below. Can someone tell me if you can use cin or not. Sorry for my bad English. The program lets you insert 5 names and then print those names to the screen.
Here's the code:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char **p = new char *[5];
for (int i = 0; i < 5; i++)
{
*(p + i) = new char[255];
} //make a 2 dimensional array of strings
for (int i = 0; i < n; i++)
{
char n[255] = "";
cout << "insert names: ";
cin >> n; //how i can use cin here to insert the string to an array??
strcpy(p[i], n);
}
for (int i = 0; i < n; i++)
{
cout << p[i] << endl; //print the names
}
}

You can indeed use something like
std::string name;
std::cin >> name;
but the reading from the stream will stop on the first white space, so a name of the form "Bathsheba Everdene" will stop just after "Bathsheba".
An alternative is
std::string name;
std::getline(std::cin, name);
which will read the whole line.
This has advantages over using a char[] buffer, as you don't need to worry about the size of the buffer, and the std::string will take care of all the memory management for you.

Use ws (whitespace) in getline() like getline(cin>>ws, name);
If numeric input is before the string then due to whitespace the first string input will be ignored. Therefore use ws like getline(cin>>ws, name);
#include <iostream>
using namespace std;
main(){
int id=0;
string name, address;
cout <<"Id? "; cin>>id;
cout <<"Name? ";
getline(cin>>ws, name);
cout <<"Address? ";
getline(cin>>ws, address);
cout <<"\nName: " <<name <<"\nAddress: " <<address;
}

Related

read .csv file and store into arrays using only <iostream> c++

Hello I am wondering what the most efficient way would be to read a .csv file and store each comma separated item into its own array or variable. I can only use #include <iostream>. I was thinking about maybe using .getLine(), but all i would know is the delimeter and value to store since there is no <fstream> allowed. That being said does anyone know how I could go about this? Thanks in advance!
This is the layout of the file. The first line indicates the umber of rows to be read.
input file
3
2014,Computer Science,Utah,1568,44.9
2014,Marketing,Michigan,23745,983
215,Business Management, Idaho,256,674
code:
int year;
char* major = new char[40];//cant be longer than 40 characters
char* state = new char[40];
int enrolled;
int rate;
char p;//for cin.get characters possibly
cin>>rows
for(int i = 0; i <= rows; i++){
HMMMMM?
}
You can use cin.getline() function which also accepts a delimiter. As for storing the entire csv record, you can define a structure which stores all the fields.
#include <iostream>
#include <cstring>
using namespace std;
typedef struct temp_struct {
char major[40];
char state[40];
float rate;
int year;
int enrolled;
} RECORD;
int main() {
int rows;
cin >> rows;
RECORD r[rows];
char temp[100];
for(int i = 0; i < rows; i++) {
cin.getline(temp, 100, ',');
r[i].year = atoi(temp);
cin.getline(temp, 100, ',');
strcpy(r[i].major, temp);
cin.getline(temp, 100, ',');
strcpy(r[i].state,temp);
cin.getline(temp, 100, ',');
r[i].enrolled = atoi(temp);
cin.getline(temp, 100);
r[i].rate = atof(temp);
cout << r[i].year << " " << r[i].major << " " << r[i].state << " ";
cout << r[i].enrolled << " " << r[i].rate << endl;
}
return 0;
}
For delimiters, the first four delimiters would be , and since the last value rate has no , following it rather there's a \n, no delimiter is specified in the cin.getline() (since default delimiter is \n itself).
I have tested it; here's the link https://ideone.com/ycht1b

How to allow unlimited number of names for input?

#include <iostream>
using namespace std;
#include "ReadString.h"
void main()
{
int i ;
int NumNames=5;
char ** pNames;
int MaxNum = 10;
int more(0);
pNames = new char *[NumNames];
cout << "Enter names" << endl;
This is the part where I am having trouble. I tried in different way but didn't work out. I tried to make a loop unless the first character is an 'Enter Key'.
while(cin.get()!='\n')
{
for (i = more; i < NumNames; i++)
{
cout << (i + 1) << ") ";
pNames[i] = ReadString();
more = NumNames;
NumNames +=NumNames
}
}
Replace manually allocated dynamic array with some container which can grow dynamically, for example std::vector:
std::vector<std::string> names;
std::string name;
// read the names
while (cin >> name) {
names.push_back(name);
}

C++ Making a char array recognise spaces upon input

I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.

reading row from text file into two vectors c++

I am trying to read the two words "kelly 1000" in the text file "players", into vectors players and balances respectively. Don't know why it's not working?
string name = "kelly";
int main()
{
int num =0;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{
input_file >> players[num];
input_file >> balances[num];
num++;
}
for(size_t i = 0; i=players.size(); i++)
{
if(name==players[i])
cout << "Welcome " << name << ", your current balance is " << balances[i] << "$." << endl;
else
break;
}
With operator[] you can only access existing elements. Going out of bounds invokes undefined behaviour. Your vectors are empty and you need to use push_back method to add elements to them.
Second problem is while (!file.eof()) anti-pattern. It'll typicaly loop one to many times because the read of last record doesn't neccesarily trigger eof. When reading from streams, always check whether input succeeded before you make use of values read. That's typicaly done by using operator>> inside loop condition.
string temp_s;
int temp_i;
while (input_file >> temp_s >> temp_i) {
players.push_back(temp_s);
balances.push_back(temp_i);
}
This way the loop stops if operator>> fails.
//Hope this is something you want dear.Enjoy
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
string name = "kelly";
int main()
{
int num =0;
string tempname;
int tempbalance;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{ input_file>>tempname;
input_file>>tempbalance;
players.push_back(tempname);
balances.push_back(tempbalance);
}
for(size_t i = 0; i<players.size(); i++)
{
if(name==players.at(i))
cout<< "Welcome " << name << ", your current balance is " << balances.at(i)<< "$." << endl;
}
return 0;
}

Indexing an array of chars - issue with pointers

#include <iostream>
#include <cstring>
using namespace std;
void getInput(char *password, int length)
{
cout << "Enter password: ";
cin >> *password;
}
int countCharacters(char* password)
{
int index = 0;
while (password[index] != "\0")
{
index++;
}
return index;
}
int main()
{
char password[];
getInput(password,7);
cout << password;
return 0;
}
Hi!
I'm trying two things here which I'm unable to do atm. I'm trying to create a char array with unspecified length in main, and I'm trying to count the number of words in the char array in the function countCharacters. But password[index] doesnt work.
EDIT: I'm doing a homework assignment, so I have to use cstrings only.
EDIT2: And I'm not allowed to use the "strlen"-function either.
At first replace
char password[];
by
char password[1000]; // Replace 1000 by any maximum limit you want
And then replace:
cin >> *password;
by
cin >> password;
Also instead of "\0" you should put '\0'
P.S. There is no char array with unspecified length in C++, you should use std::string instead(http://www.cplusplus.com/reference/string/string/):
#include <string>
int main() {
std::string password;
cin >> password;
cout << password;
return 0;
}