GetLine Function For C-String Not Working Properly - c++

I'm working on a project for my computer science class, and for whatever reason, once my code gets to my cin.getline code it just ends and doesn't allow me to enter anything in and I don't know why. I think the problem has something to do with the "null" character at the end of a c-string, but I'm not quite sure as it was working fine until I added the "Determining Whether to CODE or DECODE section" and the if statement. This code isn't fully complete yet, I just need to fix whatever is causing this to move on though.
So essentially, it works without the whole section above it and the if statement. But once I add those, my cin.getline function doesn't work. However, if I do a cin >> line, it will work even with the code above it. I need the getline function because I will be writing it to a file, and I also need to grab those sexy spaces ' '.
#include <iostream>
#include <cstring>
#include <string>
#include <ctime>
#include <fstream>
using namespace std;
//Function Prototypes:
string fileAddress(string);
void swap(char &, char &);
string code(int, char [], char [], char []);
//Main Function:
int main()
{
//Alphabet Section:
//------------------------------------------------------------------------------------------------------------------
//Declaring Variables Relating to Alphabet:
int size = 29;
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ., ";
char sAlphabet[size];
int x;
int y;
//Copying Alphabet & Outputting Test Value:
strcpy(sAlphabet, alphabet);
//Scrambling Alphabet
unsigned seed = time(0);
srand(seed);
for(int i = 0; i < 10000; i++)
{
//Initializing Random Numbers to Swap:
x = rand()%29;
y = rand()%29;
//Swapping Values
swap(sAlphabet[x], sAlphabet[y]);
}
//Testing Scrambled Alphabet:
cout << sAlphabet << endl << endl;
//------------------------------------------------------------------------------------------------------------------
//Determining Whether to CODE or DECODE Section:
//------------------------------------------------------------------------------------------------------------------
//Response Variables:
string response;
//Gathering Choice From User:
cout << "If you wish to code a message, please type CODE." << endl;
cout << "If you wish to decode a message, please type DECODE.";
cin >> response;
//------------------------------------------------------------------------------------------------------------------
//Writing Coded Message to File Section:
//------------------------------------------------------------------------------------------------------------------
if(response == "CODE")
{
//Code Variables:
int length = 100;
char line[length];
char cline[length];
string codedLine;
//Gathering Line from User:
cout << "Please enter a message in all CAPS that you wish to code.";
cin.getline(line, length);
//Copying Line:
strcpy(cline, line);
//Gathering length of Line:
length = strlen(line);
codedLine = code(length, line, cline, sAlphabet);
cout << line << endl;
cout << codedLine<< endl;
}
else
cout << "You suck";
return 0;
}
//Creating Swap Function:
void swap(char &value1, char &value2)
{
char temp;
temp = value1;
value1 = value2;
value2 = temp;
}
string code(int length, char line[], char cline[], char sAlphabet[])
{
for(int i = 0; i < length; i++)
{
//Letter A:
if(line[i] == 'A')
{
cline[i] = sAlphabet[0];
}
//Letter B:
else if(line[i] == 'B')
{
cline[i] = sAlphabet[1];
}
//Letter C:
else if(line[i] == 'C')
{
cline[i] = sAlphabet[2];
}
//Letter D:
else if(line[i] == 'D')
{
cline[i] = sAlphabet[3];
}
//Letter E:
else if(line[i] == 'E')
{
cline[i] = sAlphabet[4];
}
//Letter F:
else if(line[i] == 'F')
{
cline[i] = sAlphabet[5];
}
//Letter G:
else if(line[i] == 'G')
{
cline[i] = sAlphabet[6];
}
//Letter H:
else if(line[i] == 'H')
{
cline[i] = sAlphabet[7];
}
//Letter I:
else if(line[i] == 'I')
{
cline[i] = sAlphabet[8];
}
//Letter J:
else if(line[i] == 'J')
{
cline[i] = sAlphabet[9];
}
//Letter K:
else if(line[i] == 'K')
{
cline[i] = sAlphabet[10];
}
//Letter L:
else if(line[i] == 'L')
{
cline[i] = sAlphabet[11];
}
//Letter M:
else if(line[i] == 'M')
{
cline[i] = sAlphabet[12];
}
//Letter N:
else if(line[i] == 'N')
{
cline[i] = sAlphabet[13];
}
//Letter O:
else if(line[i] == 'O')
{
cline[i] = sAlphabet[14];
}
//Letter P:
else if(line[i] == 'P')
{
cline[i] = sAlphabet[15];
}
//Letter Q:
else if(line[i] == 'Q')
{
cline[i] = sAlphabet[16];
}
//Letter R:
else if(line[i] == 'R')
{
cline[i] = sAlphabet[17];
}
//Letter S:
else if(line[i] == 'S')
{
cline[i] = sAlphabet[18];
}
//Letter T
else if(line[i] == 'T')
{
cline[i] = sAlphabet[19];
}
//Letter U:
else if(line[i] == 'U')
{
cline[i] = sAlphabet[20];
}
//Letter V:
else if(line[i] == 'V')
{
cline[i] = sAlphabet[21];
}
//Letter W:
else if(line[i] == 'W')
{
cline[i] = sAlphabet[22];
}
//Letter X:
else if(line[i] == 'X')
{
cline[i] = sAlphabet[23];
}
//Letter Y:
else if(line[i] == 'Y')
{
cline[i] = sAlphabet[24];
}
//Letter Z:
else if(line[i] == 'Z')
{
cline[i] = sAlphabet[25];
}
//Character Period:
else if(line[i] == '.')
{
cline[i] = sAlphabet[26];
}
//Character Comma:
else if(line[i] == ',')
{
cline[i] = sAlphabet[27];
}
//Character Space:
else if(line[i] == ' ')
{
cline[i] = sAlphabet[28];
}
else
cout << "Error" << endl;
}
return cline;
}
The output should be allowing myself to write in the line of code and see it back scrambled, which the scrambler works.

I fixed it using the ignore function for the \n character found in the thread that R Sahu posted.
I basically just added:
cin.ignore(std::numeric_limits::max(), '\n')
before my cin.getline.

Related

I Have passed all the test cases for the problem and even all the test cases on Udebugg and still getting a WA verdict on UVA online judge

Judge Name- UVA Online Judge
Problem Name-Burger Time?
Problem ID-11661
Link-https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2708
I Already Tried To solve It and passed all the test cases provided in the problem pdf as well as on uDebug.Still when i submit the solution, i get a Wrong Answer Verdict.Please Help me with where i am going wrong.Thanks In Advance.
#include <iostream>
using namespace std;
int main() {
long n;
while(1) {
cin >> n;
if(n == 0) exit(0);
char ch;
long countr = 0;
cin >> ch;
char start = ch;
long ans = 1000000000;
for(long i = 1; i < n; i++) {
cin >> ch;
countr++;
if(ch == 'Z') {
ans = 0;
} else if(start == 'R' && ch == 'D') {
if(countr < ans) {
ans = countr;
}
} else if(start == 'D' && ch == 'R') {
if(countr < ans) {
ans = countr;
}
}
if(ch == 'R') {
start = ch;
countr = 0;
}
if(ch == 'D') {
start = ch;
countr = 0;
}
}
cout << ans << endl;
}
cout << endl;
return 0;
}
For
3
Z..
this code fails. Put condition for ch=='Z' ans=0 in the beginning,after you are taking the first character.

Trying to fix a string function that takes a string and change it by replacing some words

I am trying to fix a function that takes a string a checks whether it can find the numbers 4 and 5 and change them to N
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
string Newstring(string& Text);
int main()
{
while (1)
{
string head = "";
cout << "Input a string: ";
getline(cin, head);
cout << '\n';
cout << "The new string is: ";
cout << Newstring(head);
cout << '\n';
cout << "This is the end";
cin.ignore();
system("cls");
}
system("pause");
return 0;
}
string Newstring(string& Text)
{
string NewText = "";
for (int i = 0; i < Text.length(); i++)
{
if (i == '4' || i == '5')
{
i = 'N';
NewText += Text[i];
}
}
return NewText;
}
Input a string: 45fj ji
The new string is:
This is the end
This is the output and it does not show the new string
You're checking and updating the index i instead of the Text[i].
Check for
Text[i]=='4' && Text[i]=='5' and also update
Text[i]='N'
Change this:
if (i == '4' || i == '5')
{
i = 'N';
NewText += Text[i];
}
to this:
if (Text[i] == '4' || Text[i] == '5') {
NewText += 'N';
} else {
NewText += Text[i];
}
ERROR 1
you are checking if iteration through loop is equal to 4 or 5 with:
if (i == '4' || i == '5')
ERROR 2
You are assigning letter N to integer variable:
i = 'N';
But here is my ultimate solution for this problem:
std::string Newstring(const std::string& Text)
{
std::string NewText (Text);
for (int i = 0; i < Text.length(); i++)
if (NewText[i] == '4' || NewText[i] == '5')
NewText[i] = 'N';
return NewText;
}
You function need to be something like this:
string Newstring(string& Text)
{
string NewText = "";
for (int i = 0; i < Text.length(); i++)
{
if ((Text[i] == '4') || (Text[i] == '5'))
{
NewText += 'N' ;
}
else
{
NewText += Text[i];
}
}
return NewText;
}

Why I am not getting desired output for my c++ problem

I am solving a question which states: to change every '?' with 'a' in a string if doesn't contain if won't form consecutive 'a' else substitute with 'b', eg. a?b will be abb and not aab because here 2 a's are consecutive.
My problem is for i = 3 my string should be over- written with 'b ' according to my code it is entering into the desired block but the string does n't gets written with b, but in all the other case where it should be witten with 'a' it get's written .Help me out with these.
You can refer the problem statement from here to for better understanding my problem :https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/exploring-ruins/
#include <iostream>
using namespace std;
int main() {
string str;
cin >> str;
int n = str.size();
for(int i = 0; i < str.size(); i++) {
if(str[i] == '?') {
if(i == 0) {
if(str[i + 1] == 'a')
str[i] = 'b';
else
str[i] = 'a';
cout << "I am in if" << endl;
} else if(i == n - 1) {
if(str[i - 1] == 'a')
str[i] == 'b';
else
str[i] == 'a';
cout << "I am in if of else if " << endl;
} else {
if(str[i + 1] == 'a' || str[i - 1] == 'a') {
str[i] == 'b';
cout << "I am in if of else " << endl;
} else {
str[i] = 'a';
cout << "I am in else of else " << endl;
}
}
cout << str[i] << endl;
} else
continue;
}
cout << str << endl;
return 0;
}
Given string : ?ba??b
desired output : ababab
my output : aba?ab
It will be a lot easier for you if you would use functions to solve this problem.
bool check_neighbors_for_a(const string &str, size_t place) {
bool result = false;
if (place > 0) { // If there is a char before the current char
result = str[place - 1] == 'a'; // If the previous char is 'a' result become true
}
if (place < str.size() - 1) { // If there is a char after the current char
result = result || str[place + 1] == 'a'; // If the result has become true before this line, result will stay true. Else, result will be true if the next char is equal to 'a'.
// For example: b?a => result = (false || 'a' == 'a')
// For example: a?b => result = (true || 'b' == 'a')
// For example: a?a => result = (true || 'a' == 'a')
}
return result;
}
void replace_questions_by_a(string &str) {
for (size_t i = 0; i < str.size(); i++) {
if (str[i] == '?') {
if (check_neighbors_for_a(str, i)) { // If one of the neighbors is equal to 'a'
str[i] = 'b'; // Place 'b' instead of '?'
} else {
str[i] = 'a'; // Place 'a' instead of '?'
}
}
}
}

C++ Arabic numbers to Roman Numeral's & vice versa

I am writing a C++ program that converts between Arabic and Roman numbering systems. I wrote one program that converts Arabic to Roman and have another program that converts Roman to Arabic.
The problem is that I can't figure out how to merge them into one single program so that the user can input an Arabic or Roman number and as a result, the program would convert said number to the other.
My question is HOW can I merge these two programs into one?
Code for Roman to Arabic
#include <iostream>
using namespace std;
int main()
{
char roman_Numeral;
int arabic_Numeral = 0;
cout << "Enter the Roman Numeral in Capital letters (e.g. CCXIX) : ";
while (cin.get(roman_Numeral))
{
if (arabic_Numeral > 100)
{
cout << "\nInvalid Value. Number must be between I and C" << endl;
return 0;
}
else if (roman_Numeral == 'C')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D')
{
arabic_Numeral = arabic_Numeral - 100;
}
else
{
arabic_Numeral = arabic_Numeral + 100;
}
}
else if (roman_Numeral == 'L')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C')
{
arabic_Numeral = arabic_Numeral - 50;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 50;
continue;
}
}
else if (roman_Numeral == 'X')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L')
{
arabic_Numeral = arabic_Numeral - 10;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 10;
continue;
}
}
else if (roman_Numeral == 'V')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L'
|| roman_Numeral == 'X')
{
arabic_Numeral = arabic_Numeral - 5;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 5;
continue;
}
}
else if (roman_Numeral == 'I')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L'
|| roman_Numeral == 'X' || roman_Numeral == 'V')
{
arabic_Numeral = arabic_Numeral - 1;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 1;
continue;
}
}
else
break;
}
cout << arabic_Numeral << endl;
return 0;
}
Code for Arabic to Roman
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#define MAX_INPUT 100 // These constants hold high and low integer numbers,
#define MIN_INPUT 1
#define ARRAY_SIZE 4 // and the array size declarator.
string convert(int digit, string low, string mid, string high);
int main()
{
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
string strUserNum;
do
{
cout << "";
cout << "Enter an arabic number between 1 and 100: ";
cin >> strUserNum;
userNum = std::stoi(strUserNum);
if (userNum == 0 || userNum > MAX_INPUT)
{
cout << "\nInvalid Value. Number must be between 1 and 100" << endl;
return 0;
}
else if (userNum == 'end')
{
cout << "Exiting program:";
break;
}
int thous = userNum / 1000;
int hund = userNum % 1000 / 100;
int tens = userNum % 100 / 10;
int ones = userNum % 10 / 1;
answers[0] = convert(thous, "M", "M", "M");
answers[1] = convert(hund, "C", "D", "M");
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << answers[1] << answers[2];
cout << answers[3] << endl;
cout << endl;
break;
} while (userNum != 'end');
system("PAUSE");
return 0;
}
string convert(int digit, string low, string mid, string high)
{
if (digit == 1)
{
return low;
}
if (digit == 2)
{
return low + low;
}
if (digit == 3)
{
return low + low + low;
}
if (digit == 4)
{
return low + mid;
}
if (digit == 5)
{
return mid;
}
if (digit == 6)
{
return mid + low;
}
if (digit == 7)
{
return mid + low + low;
}
if (digit == 8)
{
return mid + low + low + low;
}
if (digit == 9)
{
return low + high;
}
if (digit == 0)
{
return "";
}
}
Put code (that inside the main block) for Roman to Arabic into void procedureRomanToArabic()
The same for Roman to Arabic. Put it into void procedureArabicToRoman().
Remove remove ArabicToRoman do-while and move it to main.
void procedureRomanToArabic(){
char roman_Numeral;
int arabic_Numeral = 0;
//...
cout << arabic_Numeral << endl;
}
void procedureArabicToRoman()
{
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
string strUserNum;
//remove do while here
cout << "";
cout << "Enter an arabic number between 1 and 100: ";
cin >> strUserNum;
//...
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << answers[1] << answers[2];
cout << answers[3] << endl;
cout << endl;
}
int main(){
char type;
do{
cout<<"2 for Arabic to Roman, 1 for Roman to Arabic, or anything else for exit";
cin>>type;
if(type=='1')
procedureArabicToRoman();
else if(type =='2')
procedureRomanToArabic();
else break; //end program
} while(true);
}

Post fix calculator, returns wrong value

I'm Writing a program to implement postfix calculator, its giving me completely wrong answers.
Really appreciate the help
class stacks {
public:
typedef int List;
static const int size = 100;
stacks() {
use = 0;
}
void push(List entry) {
data[use] = entry;
++use;
}
List pop() {
if(!empty()) {
--use;
return data[use];
}
}
bool empty() const {
return use == 0;
}
int Size() const {
return use;
}
private:
List data[size];
int use;
};
int main() {
stacks s;
string input;
int final;
ifstream infile("foo.txt",ios::in);
while (getline(infile, input))
cout << "Expression: ";
for (int i = 0; i<input.length(); i++) {
cout << input[i];
auto oper1 = s.pop();
auto oper2 = s.pop();
if(input[i] == '1' || input[i] == '2' || input[i] == '3' || input[i] == '4' || nput[i] == '5' || input[i] == '6' || input[i] == '7' || input[i] == '8' || input[i] == '9')
s.push(input[i] - '0');
if(input[i] == '+')
s.push(oper1 + oper2);
if(input[i] == '-')
s.push(oper1 - oper2);
if(input[i] == '*')
s.push(oper1 * oper2);
if(input[i] == '/')
s.push(oper1 / oper2);
}
final = s.pop();
cout << endl << "Value = " << final << "." << endl << endl;
}
What do you recommend?
Thanks
You need to wait to pop() until you know you have an operator. You're popping stuff off the stack when you shouldn't be.