C++ Making a char array recognise spaces upon input - c++

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.

Related

Optimize an algorithm to find multiple specific substrings of a string

I'm new to C++ coding and just started solving competitive programming problems. I want to solve the following task: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620.
I want to find a substring of a string. The problem is that the code below is slow and I fail the submission by getting the "time limit exceeded" "error". What can I do to speed up the code?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
i would make you of <algorithm> header:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
it will return iterator to where substring is. Then I wou;d use this clause:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
If there is no limitation to the use of standard libraries, It's always a better choice to use it instead of creating your own algorithms (that may not handle some special cases you won't think of ).
Also, swap those huge ugly c-style arrays to std::string.

How should I read words and put them into vectors in C++?

So the user needs to input the number of words and then input the words themselves. How should I read these words and put them into a vector ?
#include <iostream>
#include <string.h>
#include <vector>
using namespace std;
int main(){
int n;
vector<string>words;
string word;
cin >> n;
for (int i = 1; i <= n; i++){
cin >> word;
words.push_back(word);
}
cout << words;
}
I've tried this but when I run it it gives me an error saying "no match for 'operator<<' " , it's something to do with cout << words; Could any of you please explain this error as well ?
The error is coming not from reading the words, but from printing them on this line:
cout << words;
There is no overload of operator<< for std::cout that takes a std::vector<std::string>. You need to write the loop yourself:
for (auto const & word : words)
std::cout << word << " ";
Also, please don't use using namespace std;. And the correct header for std::string is <string>, not <string.h>.
You're going to need to loop through the vector and display the words one by one.
This means using:
for(int i = 0; i < words.size(); i++)
cout << words[i] << endl;
It's a syntax error to cout a vector like that.

How to build a Vector of strings (Containing Spaces)?

I was trying to build a vector of strings.
Some of the strings also contain Spaces.
That's why I was using getline(cin,string_name).
My code looks like
for(int i=0;i<n;++i)
{
getline(cin, s);
vec.push_back(s);
}
When I was taking input
ADAM BOB JOHNSON
It stopped after taking two input words, and the vector contents displayed are
(HERE SPACE IS DISPLAYED)ADAM BOB
What does it mean.Is it taking NULL string as input for the first string ?
It will be really helpful if someone tells me how to take the strings and display it.Thanks.
Abhijit,
Your information is, obviously, not enough. Assuming that your code is written on C++, I made this test cpp:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec;
std::string s;
int n = 1;
for(int i = 0; i < n; ++i)
{
getline(std::cin, s);
vec.push_back(s);
std::cout << vec.at(i) << std::endl;
}
return 0;
}
Compiled with g++ and fed it with "ADAM BOB JOHNSON" string on input. Everything worked as it planned and it output was exact same as input. So I can see no error in here.
Sorry, cannot make it a comment due to insufficient reputation so far.
UPD: Found the issue. getline first gets '\n', we left after '3' (which is needed for std::cin >> n;) hence, you just need to ignore one string. The code:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int n;
std::cin >> n;
std::vector<std::string> vec;
std::string s;
std::getline(std::cin, s);
for(int i = 0; i < n; ++i)
{
std::getline(std::cin, s);
vec.push_back(s);
// std::cout << vec.at(i) << std::endl;
}
for(int i=0;i<n;++i){
std::cout << vec[i] <<" " << std::endl;
}
return 0;
}
works fine for me.
And yep, #pmaxim98 made it first, sorry, was editing the reply and haven't seen your comment.

How to reverse the string

I'm a beginner at coding and was given a project by a friend to reverse the order of a string inputted by the user, however when I run this code the program just repeatedly prints the string inputted many times over and I'm not sure whats wrong.
For instance, I input "hi", it just prints "hi" many times. I have tried using cin, getline and scanf (as recommended by a friend), but to no avail...
#include <iostream>
using namespace std;
int main()
{
char arr[5];
getline(cin, arr);
for(int x=4; x>=0; x--){
cout << arr << endl;
}
return 0;
}
Since the question is tagged C++, you should use C++ constructs such as std::string and std::reverse. This will result in more readable and understandable code.
#include <string>
#include <iostream>
#include <algorithm>
int main()
{
std::string input;
std::getline(std::cin, input);
std::reverse(input.begin(), input.end());
std::cout << input << std::endl;
return 0;
}
This line is wrong:
cout << arr << endl;
You have to use the index operator [] like this:
cout << arr[x];
Note that there is no endl, as that would print every character in a new line.
Using arr[x] gives you the element of the array (or character of the string if you will) at index x. Please note that element indexes in C++ start at 0. So the first element is arr[0], second arr[1], and so on.
Also, why use a C-style char array of only size 5? You can use the C++ std::string just as effectively and it will work for larger strings:
string x;
getline(cin, x);
for (int i = x.size() - 1; i >= 0; i--)
{
cout << x[i];
}
cout << endl;
Hope this helps.
When you write, cout << arr << endl; you are printing the entire string in each iteration of the loop. Instead, you wish to print the character at the index x, so you should write it as cout << arr[x]; If you use endl inside the loop, you will get a new line after each character.
Moreover, in C++, there is an easier way to deal with strings, using the string library. Then, you need not specify the number of characters in your string beforehand, and helps if the user needs to enter more than 4 characters.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string arr;
getline(cin, arr);
for(int x=arr.size()-1; x>=0; x--){
cout << arr[x];
}
cout << endl;
return 0;
}
What's happening is you're sending the entire contents of arr to cout 5 times. What you want instead is to print each character in reverse; to do this, you need to send only one character of arr at a time inside your for loop:
cout << arr[x] // This sends the character at index x to cout
cout << arr // This sends the entire array to cout
Also, you should have cout << endl after the for loop; otherwise, you'll print a newline character after each letter.
Alternate solution using iterators:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
int main()
{
std::string input;
getline(std::cin, input);
for (std::string::reverse_iterator rit=input.rbegin(); rit!=input.rend(); ++rit)
std::cout << *rit;
return 0;
}

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;
}