Can someone explain the error in this while loop? - c++

So I'm a beginner programmer... and I can't figure out what the problem is in this bit of code I'm writing for a text adventure. All I want it do At the moment is let the user enter a command, and then it converts it to ALLCAPS and prints that out. It should output this:
What shall I do?
pie
Your raw command was: PIE
But instead, it outputs this:
What shall I do?
pie
PIE
...and then it freezes. Here's the code:
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <vector>
using namespace std;
void command_case();
string userIn;
string raw_command;
int x = 0;
int main()
{
while(raw_command != "QUIT")
{
cout << "What shall I do?\n";
cin >> userIn;
command_case();
cout << "Your raw command was: " << raw_command << endl;
}
return 0;
}
void command_case()
{
char command[userIn.size()+1];
strcpy(command, userIn.c_str());
while(x < userIn.size()+1)
{
if(islower(command[x]))
{
command[x] = toupper(command[x]);
cout << command[x];
x++;
}
else if(isupper(command[x]))
{
cout << command[x];
x++;
}
}
raw_command = command;
}
I think it may be a problem with the while loop in void command_case(), but I can't figure out exactly what that problem is. I'd appreciate any advice you can give me.

One too much:
while(x < userIn.size()+1)

The problem is with the x variable in the command_case() function.
When x becomes 3 (and "command[x] points to the null character at the end of "pie")
neither islower(command[x]) or isupper(command[x]) are true.
Neither section of the if statement executes, so x stays at 3 forever.
Since "userIn.size()+1" is 4, and x never reaches 4, the loop never exits.
A possible solution is remove the "x++" from both sections of the if statement, and have a single "x++" after the if statement. This will increment x during every loop regardless of what character "command[x]" points to.

You could easily do something like
void command_case()
{
for(int i =0; i<userIn.size(); i++)
{
userIn[i] = toupper(userIn[i]);
}
}
then cout<<userIn in the main

You should remove all cout calls from command_case() function. In fact the whole if-branch in the function is useless and you could just replace it with the following:
command[x]=toupper(command[x]);
For the simplicity you could replace the whole command_case() function with (just remember to #include <algorithm>):
std::transform(userIn.begin(), userIn.end(), userIn.begin(), toupper);

Related

Exception case: checking to see if the element already exists in an array c++

I'm currently learning c++. I got stuck in this little problem with the exception.
A program asks users to enter 5 integers in an array. I need the program to manage an exception that requests the input of an element again if it already exists.
Here is my code, I figured out the global structure, but the problem is if you enter 0 the program will throw out an exception "already exists", that's not the result I wanted. I know where this comes from, T[j] was not defined in for loop, but I don't know how to deal with it. Could anyone help me to improve it, please? other solutions are also welcomed.
#include<iostream>
#include <vector>
#include<cstdlib>
using namespace std;
int main(){
int i=0,j=0;
int temp;
vector<int>T(5);
do{
try{
cout<<"user input "<<(i+1)<<":";
cin>>temp;
//T[j]= 'a000000000000000000'; //I tried to define T[j], that's maximum I can do
for(j=0;j<=i;j++){
if(T[i]==T[j])
throw(0);
}
T[i]=temp;
i++;
}
catch(const int){
cout<<"Error: value already exists, try again"<<endl;
}
} while(i<sizeof(T)/sizeof(int));
for(i=0;i<sizeof(T)/sizeof(int);i++){
cout<<T[i]<<endl;
}
return 0;
}
This line creates a vector which contains 5 ints. All ints in the vector are zero:
vector<int>T(5);
This line runs a loop. Since i is zero, it runs the loop one time, where j is equal to zero, because j<=i is true, because both of them are zero.
for(j=0;j<=i;j++){
This line checks whether T[i] equals T[j], which it does, because i and j are both zero, and T[0] equals T[0].
if(T[i]==T[j])
This line throws an exception.
throw(0);
Did you spot the bug yet? Maybe you don't want to run the loop where j is equal to i. Maybe you want to loop while j<i instead of j<=i. So if i is 5, j goes from 0 to 4 instead of 0 to 5, and if i is 0, the loop does not run at all.
Also, as Mark Ransom pointed out, this is wrong:
sizeof(T)/sizeof(int)
It should be
T.size()
sizeof(T)/sizeof(int) would work for an array, but not for a vector. You want T.size() instead.
If there isn't a requirement for the numbers to be output in the same order as they were input, a std::set (or std::unordered_set) would work well
#include <iostream>
#include <set>
int main()
{
constexpr int NUMBERS_TO_READ{5};
std::set<int> numbers;
int i = 0;
do
{
int temp;
std::cout << "user input " << (i+1) << std::endl;
std::cin >> temp;
if (numbers.find(temp) != numbers.end())
{
//temp is already in the set
std::cout << "Value " << temp << " already exists, try again!" << std::endl;
}
else
{
//temp isn't in the set. add it.
numbers.insert(temp);
i++;
}
}
while (i < NUMBERS_TO_READ);
for (const auto num : numbers) std::cout << num << std::endl;
}

How can I make a second cout without destroying my first in this program?

#include "stdafx.h"
#include "iostream"
#include "thread"
#include "conio.h"
#include "windows.h"
using namespace std;
void incrm();
void charget();
void main() {
thread count(incrm);
thread getcin(charget);
count.join();
getcin.join();
cin.get();
}
void incrm() {
int j = 0; // used to increment and output
while (true) {
cout << "\r" << j; // outputs 1,2,3,4... and so on
j++;
Sleep(150);
}
cout << endl;
}
void charget() {
while (true) {
int i = getch(); // gets value of char
cout << "\r\nCHAR: " << i; // and here is the problem...!
}
}
So I wanted this program to output a number in the first line, which increments without stopping and if you hit any key it should cout the value of that key in a secound line, so i wanted it to output something like this->
45
CHAR: 97
and after you have hit a key the incrementing number should stay in the first line. If you hit several keys the second cout should be overwritten, but this doesnt seem to work for me, my output looks like this if i hit several keys->
10
12AR: 97
20AR: 96
My problem is that my first cout (the incrementing number) overwrites my second (or my second my first I don't really know) and then this countinues for every line! :(
I suggest you to use windows function called gotoxy(). You can apply this using
SetConsoleCursorPosition();
this function is availible in windows.h library.
It is possible to read more about it here:
Link

Strange output from C++ in Linux Terminal

I've recently started learning programming using the C++ language. I wrote a simple program that is supposed to reverse a string which I compile in the Terminal using gcc/g++.
#include <iostream>
using namespace std;
string reverse_string(string str)
{
string newstring = "";
int index = -1;
while (str.length() != newstring.length())
{
newstring.append(1, str[index]);
index -= 1;
}
return newstring;
}
int main()
{
string x;
cout << "Type something: "; cin >> x;
string s = reverse_string(x);
cout << s << endl;
return 0;
}
I've rewritten it multiple times but I always get the same output:
Type something: banana
��
Has anyone had a problem like this or know how to fix it?
Your code initializes index to -1, and then uses str[index] but a negative index has no rational meaning in C++. Try instead initializing it like so:
index = str.length() - 1;
I can see several issues with your code. Firstly, you are initializing index to -1, and then decrementing it. Maybe you meant auto index = str.length()-1;?
I recommend you look at std::reverse, which will do the job you're after.
Your main function then becomes:
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string x;
cout << "Type something: ";
cin >> x;
reverse(x.begin(), x.end());
cout << x << endl;
return 0;
}
If you really want to write your own reverse function, I recommend iterators over array indices. See std::reverse_iterator for another approach.
Note, the above will simply reverse the order of bytes within the string. Whilst this is fine for ASCII, it will not work for multi-byte encodings, such as UTF-8.
You should use a memory debugger like valgrind.
It's a good practice to scan your binary with it, and will make you save so much time.

Getting multiple lines of input in C++

The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
(Source: http://codeforces.com/problemset/problem/71/A)
How would you get input from the user given n? I tried using a while loop but it doesn't work:
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int i;
while (i<=n) {
cin>>i ;
i++;
}
}
You probably meant to have something like:
#include <iostream>
int main() {
int n;
cin>>n;
int theInputNumbers[n];
for(int i = 0; i<n; ++i) {
cin >> theInputNumbers[i];
}
}
Your loop is really quite far off of what you need. What you wrote is extremely wrong such that I cannot provide advice other than to learn the basics of loops, variables, and input. The assistance you need is beyond the scope of a simple question/answer, you should consider buying a book and working through it cover to cover. Consider reading Programming Principles and Practice Using C++
Here is a working example of something approximating your question's requirements. I leave file input and output as an exercise up to you. I also make use of C++11's front and back std::string members. You would have to access via array index in older versions.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
int totalWords;
cin >> totalWords;
stringstream finalOutput;
for (int i = 0; i < totalWords; ++i){
string word;
cin >> word;
if (word.length() > 10){
finalOutput << word.front() << (word.length() - 2) << word.back();
}else{
finalOutput << word;
}
finalOutput << endl;
}
cout << endl << "_____________" << endl << "Output:" << endl;
cout << finalOutput.str() << endl;
}
With that said, let me give you some advice:
Name your variables meaningfully. "int i" in a for loop like I have above is a common idiom, the "i" stands for index. But typically you want to avoid using i for anything else. Instead of n, call it totalWords or something similar.
Also, ensure all variables are initialized before accessing them. When you first enter your while loop i has no defined value. This means it could contain anything, and, indeed, your program could do anything as it is undefined behavior.
And as an aside: Why are you reading into an integer i in your example? Why are you then incrementing it? What is the purpose of that? If you read in input from the user, they could type 0, then you increment by 1 setting it to 1... The next iteration maybe they'll type -1 and you'll increment it by 1 and set it to 0... Then they could type in 10001451 and you increment by 1 and set it to 10001452... Do you see the problem with the logic here?
It seems like you are trying to use i as a counter for the total number of iterations. If you are doing this, do not also read input into i from the user. That completely undermines the purpose. Use a separate variable as in my example.

passing array as parameter to a function

this script is supposed to output array values that were inputted by the user into array "store." I am trying to store all the char array values into string temp. I get the error on line 12: "[Error] invalid conversion from 'char*' to 'char' [-fpermissive]." Would appreciate any help!
Edit: so I fixed the declaration and now at least it compiles, but the answer I get on my cmd is all jumbled up. Why is this so? The cmd only correctly couts the first string but after the space, it messes up.
#include <iostream>
#include <cstdlib>
using namespace std;
void coutArray(char[], int);
int main()
{
char store[50];
cout << "enter text: " << endl;
cin >> store;
coutArray(store, 50);
system("pause");
return 0;
}
void coutArray(char store[], int max)
{
string temp = "";
int i = 0;
while (i < max)
{
temp += store[i];
i++;
}
cout << temp << endl;
}
Using input from all answerers I finally got the fixed code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void coutArray(char[], int);
int main()
{
char store[50] = {0};
cout << "enter text: " << endl;
cin.getline(store, 50);
coutArray(store, 50);
system("pause");
return 0;
}
void coutArray(char store[], int max)
{
string temp = "";
int i = 0;
while (i < max && store[i]!=0)
{
temp += store[i];
i++;
}
cout << temp << endl;
}
Thanks everyone. i learned a lot!!!
When you get an input using "cin" your input automatically ends with 0 (NULL).
You just need to add one little piece of code to your while statement.
instead of this :
while (i < max)
use this :
while (i < max && store[i]!=0)
Now it will stop when the input string is finished and won't print any garbage existed in the array beforehand.
To show that cin does add terminating zero, i initialized the array to 46, and put a breakpoint after the cin
so I fixed the declaration and now at least it compiles, but the answer I get on my cmd is all jumbled up. Why is this so?
Not sure what you mean by jumbled up. But since you did not tell us what you typed its hard to know it looks like it worked to me:
> ./a.out
enter text:
Plop
Plop�ȏU�
Notice that since my input is only 4 characters long. This means that a lot of the characters in the array still have undefined (ie random values). This is why I am seeing junk. To get past this initialize the array to have all 0 values.
char store[50] = {0};
Even bettern use a C++ object than handles longer strings.
std::string store;
std::getline(std::cin, store);
Note: passing arrays to functions by value is not a good idea. On the other end they have decayed to pointers and thus do not act like arrays anymore (they act like pointers whose semantics are similar but not identical).
If you must pass an array pass it by reference. But I would use a C++ container and pass that by reference (it is much safer than using C constructs). Have a look at std::string
The declaration of the function is wrong. Should be void coutArray(char *, int);
Look at the Implicit Conversion rules to understand what the compiler can do and what it cannot to do for you.
The issue with your program was that you were probably entering in less characters than the maximum size of the buffer. Then when you passed the maximum size as the parameter to coutArray, you assigned unfilled slots in the char array to temp. These unfilled slots could contain anything, as you have not filled them up to that point.
Your program is still correct, but what would be better would be to use read so that the number of bytes you specify is the minimum number of bytes that can be entered:
std::cin.read(store, 50);
Even better solution would be to use std::string:
std::string store;
std::cin >> store;
// or for the entire line
std::getline(std::cin, store);
It also follows that your coutArray should be changed to:
void coutArray(std::string);
// ...
void coutArray(std::string str)
{
std::cout << str << std::endl;
}
Look at this way
template<typename T, size_t N>
void MyMethod(T (&myArray)[N])
{
//N is number of elements, myArray is the array
std::cout<<"array elements number = "<<N<<endl;
//put your code
string temp;
temp.resize(N+1);//this is for performance not to copy it each time you use += operator
int i = 0;
while (i < max)
{
temp += store[i];
i++;
}
cout << temp << endl;
}
//call it like this
char arr[] = "hello world";
MyMethod(arr);