continuous input characters like strings using loop multiple times - c++

In the following code, is it possible that I take multiple input, do some calculation (like the last character) and print at the end .. and then again take input till 5 times?
#include <iostream>
using namespace std;
int main ()
{
char name;
int i=0;
while(i != 5){
while(!(name != '<' || name != '>')){
cin>>name;
//do some calculation with the inputs
//cout<<name;
}
i++;
cout<<name;
//print the result of calculation this loop
}
}
For some reason, I am not allowed to use string, or array, or break, and no library other than iostream. Is it possible using loops? What are alternatives?
EDIT:: In above code, I want to determine what was last input. If I enter asdf> then i get >>>>>. I want it to print > and go back in the loop and ask me for another shot.

After the inner while terminates name holds either < or > and is not reset prior to the next encounter of the inner while, which terminates immediately as name is still either < or >. Just reset name prior to the inner while or slight restructure:
while (cin >> name && !(name != '<' || name != '>'))
{
}

The solution is to reset the name variable right before this line:
while (!(name != '<' || name != '>')) {
What you need to do would be this:
name = 0;
Also, I'd recommend initializing the variable before entering the first while loop.
Edit:
Alternatively, you can use '\0' instead of 0. It makes no difference internally though. The code would only make more sense to most inexperienced users.

Looks like you want to make a pointer to a character. This will behave just like an array without actually being an array, and requires nothing but #include <iostream> for the input and output.
char* name;
You could also try using a vector of characters, but this is the long way around and would break the "nothing but <iostream> rule:
#include <vector>
#include <iostream>
using namespace std;
vector<char> CharVec;
vector<char>::iterator it;
int main ()
{
char input;
int i=0;
while(i != 5){
if(input != '<'){ //this should be if, not while
CharVec.push_back(input);
}
i++;
}
//move print to outside the character entering loop
it = CharVec.begin();
while(it != CharVec.end())
{
cout << *it;
it++;
}
}

Related

vector find is returning the wrong value

The purpose of this program is to read strings from a .txt file and put all the non-repeating words into a set. I did this by putting all the words into a vector and then attempted to go through it and add only the unique words to the set and deleting the repeating words from the vector. Here is my complete code with the part I am having trouble with at the bottom.
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main ()
{
//create data types
set<string> non_duplicate;
vector<string> vectorstring;
vector<string>::iterator it;
ifstream file;
//open file return 1 if can't be opened
file.open ("txt.txt");
if (!file.is_open()) return 1;
//make variable for word
string word;
//take words one at a time from file and add to vector/
while (file >> word)
{
vectorstring.push_back(word);
}
//check vector from repeats and add to set if not
do
{
string temp = vectorstring[0];
vectorstring.erase(vectorstring.begin());
bool duplicate = 0;
check:
if (vectorstring.size() == 0)
{
non_duplicate.insert (temp);
break;
}
it = find(vectorstring.begin(), vectorstring.end(), temp);
if (*it != temp && duplicate != 1)
{
non_duplicate.insert (temp);
}
else if (*it == temp)
{
vectorstring.erase(it);
duplicate = 1;
goto check;
}
} while (!vectorstring.empty());
//output results
cout << "List of non-repeating words: ";
for (auto x = non_duplicate.begin(); x !=non_duplicate.end(); x++)
{
cout << *x << " ";
}
cout << endl;
This is the bit of code causing me problems. Everytime I get towards the last 3ish elements in the vector the find function and "it" do not give me the correct output. For instance if the temp value being searched for is "ben" and the last of these words has been deleted the value of it does not reset and stays "ben" after going through find making it seem as though there is still a value of "ben" when there is not. I'm not sure why this is happening since it works on every value except those near the end?
do
{
string temp = vectorstring[0];
vectorstring.erase(vectorstring.begin());
bool duplicate = 0;
if (vectorstring.size() == 0)
{
non_duplicate.insert (temp);
break;
}
check:
it = find(vectorstring.begin(), vectorstring.end(), temp);
if (*it != temp && duplicate != 1)
{
non_duplicate.insert (temp);
}
else if (*it == temp)
{
vectorstring.erase(it);
duplicate = 1;
goto check;
}
} while (!vectorstring.empty());
To get a std::set with unique entries from a std::vector you merely have to construct the set. A set contains only unique entries by definition:
#include <set>
#include <vector>
#include <iostream>
int main() {
std::vector<int> x{1,1,2,2,3,3};
std::set<int> non_duplicate{x.begin(),x.end()};
for (const auto n : non_duplicate) std::cout << n << " ";
}
Output:
1 2 3
Your code is too complicated. I spotted at least one major issue:
string temp = vectorstring[0];
vectorstring.erase(vectorstring.begin());
//....
it = find(vectorstring.begin(), vectorstring.end(), temp);
if (*it != temp && duplicate != 1)
When the first element vectorstring[0] appear only once in the vector, then find will return vectorstring.end() (because the one appearance you erased). Dereferencing the end iterator as in *it != temp invokes undefined behavior.
std::set will store elements only once. You could simply store everything in the set directly without getting a vector involved.
std::string word;
while (file >> word)
{
non_duplicate.insert(word);
}
Furthermore dereferencing the end iterator is undefined behaviour. If no match is found std::find returns the second iterator, you'll dereference the end iterator of the vector in the if conditions.
Moreover the use of goto should be avoided, since it can easily result in code that is hard to maintain. In your case it wouldn't be hard to rewrite the code to use a second nested loop instead.
Also the loop does make the assumption that the vector is not initially empty.
Here's a rewrite of your loop though that would work:
while(!vectorstring.empty())
{
std::string temp = std::move(vectorstring[0]); // don't make a copy; we'll erase the object anyways
vectorstring.erase(vectorstring.begin());
// clear the duplicates from the vector
/* Note: We could just use the following more efficient one-liner for this
vectorstring.erase(std::remove(vectorstring.begin(), vectorstring.end(), temp), vectorstring.end());
*/
for (auto it = std::find(vectorstring.begin(), vectorstring.end(), temp); it != vectorstring.end(); it = std::find(vectorstring.begin(), vectorstring.end(), temp))
{
vectorstring.erase(it);
}
}

how to insert space separated input into an array in C++ [duplicate]

A String is given as an input which consists of numbers and I want to convert it into integer arrays in C++.
#include <string>
#include <iostream>
#include <sstream>
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
int main(int argc,char** argv) {
string num="-24 2 90 24 50 76";
stringstream stream(num);
while(stream){
int n;
stream>>n;
cout<<n<<endl;
}
return 0;
}
Output(GCC) :
-24 2 90 24 50 76 76
Why am i getting extra value and what is the efficient to convert them into integer array ?
UPDATE:
What if the string stream contains delimiter other than space, How to parse this?
For eg:
string num="-24,2,90,24,50,76";
The end of file condition is not set upon a succesful parse, you have to check the state of the stream after parsing.
The second 76 is basically just pure chance. An unsuccesful parse leaves the target operand untouched, and because you did not initialize n, it can be anything.
A quickfix:
stream>>n;
if (stream)
cout<<n<<endl;
A cleaner fix:
int n;
while(stream >> n){
cout<<n<<endl;
}
To store those integers, the canonical way is to use std::vector if the number of elements is unknown. An example usage:
std::vector<int> values;
int n;
while(stream >> n){
...do something with n...
values.push_back(n);
}
However, you can use iterators over streams and use the following:
// Use std::vector's range constructor
std::vector<int> values(
(std::istream_iterator<int>(stream)), // begin
(std::istream_iterator<int>())); // end
Another means of dealing with a character separated integers list using a vector, which is even perhaps a little more simplistic is more like this:
string str = "50,2,25,38,9,16";
vector<int> ints;
stringstream ss(str);
int n;
char ch;
while(ss >> n) {
if(ss >> ch)
ints.push_back(n);
else
ints.push_back(n);
}
that way you can move past any character separations (if they exist) first and then default back to grabbing the integers and adding them to the list if they don't (AKA the end of the list)
i don't know if you find the answer for your updated question or not. if you don't you can easily do it by the code
for (string::iterator it = num.begin(); it != num.end(); ++it) {
if (*it == ',') {
*it = ' ';
}
else continue;
}
this code removes all your colons and replaces them by space. then you can do just normally

Logical Issue or Syntax issue with sorting String function

I'm new to C++ and coding in general. I'm attempting to make a simple program that essentially takes in two words and will tell you if these two words are anagrams or not.I also understand that there is likely a pre-made function to sort a string, like an array however I am trying to grasp the concept itself and hence why I'm attempting to make the function.
Here is a quick snippet of the code I've written so far.
Snippet of code
The issue that I'm currently having is that when I call the function to sort the string, the string isn't sorted! Sorry if there is a simple solution to this, I'm fairly new. Is this a logical issue or syntax based? Thank you so much!
#include <iostream>
#include <string>
using namespace std;
//Function Declarations
string sortString(string user_input);
//Program Body
int main()
{
string user_input_one, user_input_two;
cout << "Welcome to Sandip's Anagram Checker! \nPlease Input two words that you'd like the check!";
sortString(user_input_one);
sortString(user_input_two);
if (user_input_one == user_input_two)
cout << "These two words are Anagrams of each other!";
else
cout << "These are not Anagrams!";
return 0;
}
//Function Definations
string sortString(string user_input)
{
string temp_string = user_input;
int i,j;
for (i = 0; i<user_input.length();i++)
{
for (j=0; j<user_input.length();j++)
{
if (user_input[i] == user_input[j])
{
temp_string[i] = user_input[j];
}
else if (user_input[i] > user_input[j])
{
temp_string[i] = user_input[j];
}
else if (user_input[i] < user_input[j])
{
temp_string[i] = user_input[i];
}
}
}
return temp_string;
}
Adding to Daniel's answer, you don't need a temporary string in the sorting function, just process the passed string and return it. Also consider supporting letter cases as well, you can use std::transform from the STL algorithm library.
#include <algorithm>
Add this before looping in your sorting function or after taking inputs in main.
transform(user_input.begin(), user_input.end(), user_input.begin(), ::tolower);
There are a couple issues. You're not actually reading any user input. You can fix this by adding cin >> user_input_one >> user_input_two;.
Your sorting also doesn't work quite right. It looks similar to selection sort, so I tweaked it to be a variation of that. For each character in the string, it goes through the rest of the string and swaps letters if the later one should be first.
string temp_string = user_input;
int i, j;
for (i = 0; i < user_input.length(); i++)
{
for (j = i + 1; j < user_input.length(); j++)
{
if (temp_string[j] < temp_string[i]) {
swap(temp_string[i], temp_string[j]);
}
}
}
return temp_string;
Lastly, as #cigien commented, you aren't using the sorted result. You can change this by replacing your lines calling sortstring() with this:
user_input_one = sortString(user_input_one);
user_input_two = sortString(user_input_two);

error: invalid conversion from 'char' to 'const char*' in palindrome program

This code is an attempt to test whether or not a string is a palindrome. It reads a string of characters, pushing each character onto a stack as it is read and simultaneously adding it to a queue. Then, it uses basic stack and queue operations to determine if the string is a palindrome.
The program blows up with the aforementioned error(s) when it hits:
inStack.push(inString[i]);
inQueue.push(inString[i]);
and I don't understand why, or how to fix it. The research I have done looking into this error as it applies to my case hasn't been fruitful. I'm fairly new to c++ so forgive me if I'm overlooking something stupid.
The code is as follows:
#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
int main()
{
stack <string> inStack;
queue <string> inQueue;
string inString; //user input
int inLength; //loop counter variable
bool isPalindrome(false);
cout<<"Enter a word to see if it is a palindrome: ";
cin>>inString;
if (inString.size() > 0)
{
for (int i = 0; i <= inLength; i++)
{
inStack.push(inString[i]); //put string chars onto stack
inQueue.push(inString[i]); //add string chars to queue
}
isPalindrome = true;
while (isPalindrome && (!inStack.empty()) && (!inQueue.empty()))
{
if (inStack.top() != inQueue.front())
{
isPalindrome = false;
}
else
{
inStack.pop();
inQueue.pop();
}
}
}
if(isPalindrome == false)
{
cout<<"It is not a palindrome."<<endl;
}
else
{
cout<<"It is indeed a palindrome."<<endl;
}
return 0;
}
There are three main errors in your code.
You are pushing characters onto a stack and a queue that are defined to hold strings. The string constructor cannot implicitly convert from char to string, since there is no constructor that takes a char. You probably meant to define them as:
stack<char> inStack;
queue<char> inQueue;
You didn't set inLength; I suggest adding something like
inLength = inString.size();
after your if (inString.size() > 0) { to fix that.
Most important, you use i <= inLength (in your for loop condition), which won't work; you should use <, since pushing inString[inString.size()] is actually pushing one character beyond what you enter, which will always result in isPalindrome == false since your stack and queue will have an invalid (random garbage) character at the corresponding top and front.
These three changes appear to be enough to fix your project.
A simpler solution to give you an example of how C++ iterators can be used to reduce the amount of code you have to write for these kinds of things:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<char> left, right; // left-to-right and right-to-left lists
cout<<"Enter a word to see if it is a palindrome: ";
string inString; //user input
cin>>inString;
if(!inString.empty()){
// add characters left to right
left.insert(left.end(), inString.begin(), inString.end());
// add characters in reverse order, right to left
right.insert(right.end(), inString.rbegin(), inString.rend());
// compare the two vectors
if(left == right)
cout<<"It is indeed a palindrome."<<endl;
else
cout<<"It is not a palindrome."<<endl;
}
}
You forgot to assign to inLength the actual length of the string and get a outside i gets very big, bigger than it should be and you probably get a segmentation fault.
Try after reading the string to assign the value properly.
inLength = inString.size();
I hope this helps you.

C++ Find word in sentence

I've got a task to find the word "EYE" in a sentence (more like just line of chars) such as: EYEYECARASDFG. As you can see, the word "EYE" is there twice, overlapping each other. I am suppose to cout how many times the word "EYE" occurs in the sentence. I wrote some code that looks like this:
#include <iostream>
#include <string>
using namespace std;
string sentence;
int main()
{
int i = 0;
cin >> sentence;
while()
{
if (std::string::npos != sentence.find("EYE"))
{
i++;
}
}
cout << i;
}
Now without the while loop, it finds the EYE in the sentence and it kinda works. So I though, to count with the overlapping and make the code running until it hits the end, I need to loop it. So I though the while loop would be the best, but I don't know how to loop it, what to put into the brackets for while loop
First of all condition in while is required. If you want infinite loop use true as your statement. As a first draft, try to make it with "brute force". Just check every 3 letters substring of your sentence if equals "EYE". It will be one loop and 3 conditions or 2 loops and 1 condition. Then read about some text search algorithm e.g KMP.
If you just want to make this code run use following coed:
int pos = 0;
while(true) {
pos = sentence.find("EYE", ++pos);
if (pos != std::string::npos) {
i++;
} else break;
}
You can do this using a finite-state machine. (Google it.) That is efficient and easy to understand. As you read the characters, there are three states to distinguish, i.e., 1) when the most recent letter seen was an "E", 2) when the last two seen were "EY" in that order, and 3) everything else. As you go through a character at at time, increase the "found"-count by one whenever you are in state 2 and find another "E".
See if you can take it from there with no more hints.
The idea can be extended to arbitrary strings besides "EYE", and you can write a compiler of sorts to generate the finite-state machines for those strings. But that is a more advanced assignment.
#include<iostream>
#include<string>
using namespace std;
main()
{
string sen, sub;
int pos;
cout<<"Enter the Sentence"<<endl;
getline(cin,sen);
cout<<"Enter string to find"<<e`ndl;
cin>>sub;
for (int i=1;(pos=sen.find(sub)) != -1 ;i++)
{
sen=sen.substr(++pos);
cout<<"Found = "<<sub<<" "<<i<<" Times"<<endl;
}``
}
Code Snippet :
#include <bits/stdc++.h>
using namespace std;
int main()
{
string input, word;
getline(cin, input);
cin>>word;
int cnt=0;
size_t pos = input.find(word, 0);
while(pos != string::npos)
{
cnt++;
pos = input.find(word, pos+1);
}
cout<<cnt<<endl;
return 0;
}
Input :
Python Programming Python
Python
Output : 2