I need help in c++. I want to compare char array. So, I did some coding. Unfortunately, it always comes out an error. I can't run it. Here I attached the code. Please help me fix this code. I want to check if the conclusion equal to sentence 1 then it is invalid but if it's not equal sentence 1 then it is valid. Help me, please. Thank you.
int number;
char sentence[number];
char rules[50];
char statement[50];
char premis1[100];
char premis2[100];
char conclusion[100];
cout<<"How many sentence you want to insert:";
cin>>number;
cout<<endl;
for(int i=0; i<number; i++)
{
cout<<"Enter sentence ";
cout<<i+1;
cout<<":";
cin>>sentence[i];
cin.ignore();
}
cout<<"Enter premis 1:";
cin.getline(premis1,100);
cin.ignore();
cout<<"Enter premis 2:";
cin.getline(premis2,100);
cin.ignore();
cout<<"Enter conclusion:";
cin.getline(conclusion,100);
cin.ignore();
for(int i=0;i<number;i++)
{
if(strcmp(conclusion,sentence[0],)==0)
{
cout<<"Statement is invalid."<<endl;
cout<<endl;
}
else if(strcmp(conclusion,sentence[0])!=0)
{
cout<<"Statement is valid."<<endl;
}
else
cout<<"exit"<<endl;
}
Your mistakes you've made in the program:
You never initialized number but used in sentence[], still it's invalid even after number's declaration, that's because the compiler must know the exact value of the array length to be defined.
You've defined sentence as a char array but from your code, it seems like you wanted to store a full sentence into each element of array, which is impossible. Use std::string here.
You're doing strcmp() with the first character of char array, not the sentence with conclusion.
Aside: Please don't forget to include the important header files which are common to the code and we must assume your program is incomplete, because it has a lack of main() and statement(s), such as strcmp(...,...',' - incomplete).
Redesigned the program (notice that using namespace std statement is used here because it's just a small program to demonstrate and for sake of simplicity and getting rid of std:: prefixes everywhere):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(void) {
int number = 0;
vector<string> sentence;
string tempSentence;
string conclusion;
cout << endl;
cout << "How many sentences you want to insert? ";
cin >> number;
for (int i = 0; i < number; i++) {
fflush(stdin);
cout << "Enter sentence " << (i + 1) << ": ";
getline(cin, tempSentence);
sentence.push_back(tempSentence);
}
cout << "Enter conclusion: ";
getline(cin, conclusion);
if (conclusion == sentence[0])
cout << "The statement is invalid." << endl;
else if (conclusion != sentence[0])
cout << "The statement is valid." << endl;
else
cout << "EXIT" << endl;
return 0;
}
I've taken std::vector<> of std::string here to insert a single string in defined number of sentences given in a dynamic way in each iteration (from #include <vector>) and used std::string rather than char arr[], it's easy to compare strings here.
Sample Output:
$ g++ -o prog prog.cpp; ./prog
How many sentences you want to insert? 3 // --- INPUT
Enter sentence 1: This is the first sentence.
Enter sentence 2: This is the second sentence.
Enter sentence 3: This is the third sentence.
Enter conclusion: This is NOT the first sentence.
The statement is valid. // first sentence != conclusion // --- OUTPUT
Related
Current code:
const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team {
string TeamName[MAX_CODENAME];
short int totalLeagueGames;
short int leagueWins;
short int leagueLoses;
};
//GLOBAL VARIABLES:
Team league[MAX_SPOTS];
void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
cout << "****** ADD TEAMS ******" << endl;
cout << "Enter the teams name " << endl;
scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
if(decider == league[i].TeamName){
cout << endl;
cout << league[i].TeamName << endl;
break;
}else{
cout << "Searching...." << endl;
}
}
}
I really dont know why its not working but I have included all the perquisite header files such as and but the program crashes when i enter the data and then attempt to search. I get the circle of death and then program not responding then says Process returned 255 (0xFF) . It does not even out put Searching.... the program practically gives up as soon as I enter that name.
Also if this can be optimized by the use of pointers that would be great.
tl;dr run-time error causing the search to fail as soon as i type in a name. And for the record I have checked to make sure the name I entered is valid.
scanf doesn't know about std::string. Use std::cin >> league[i].TeamName.
scanf("%s", league[i].TeamName) ;
This should be changed to
std::cin >> league[i].TeamName ;
A couple of other things here....
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
Every time you input a value, you are telling the computer to hold the inputted value at decider[25] but the computer only reads indexes 0-24.
if(decider == league[i].TeamName){
Which array slot are you comparing the team name to? If its the 25th element than the statement should be
if(decider[24] == league[i].TeamName){
Pointers are better suited if the number of TeamNames are unknown. Based on the limited code presented, I highly recommend you stay within the realm of basic data types. For the purposes of troubleshooting, please post your full code in the future.
Your TeamName member variable:
string TeamName[MAX_CODENAME];
is an array of 25 strings, so in this line:
scanf("%s", league[i].TeamName) ;
you are courrupting the array. You don't really want an array anyways, so change the TeamName declaration to:
string TeamName;
and then when you read the name, you'll need to use iostreams which knows how to populate a string type (scanf only works with c char arrays):
std::cin >> league[i].TeamName
I've looked everywhere, but I cannot find a solution to exactly why this happens in my situation.
I'm making a simple string function that asks for a string, and prints out the length.
However, I get an "Invalid Null Pointer" assertion error when I run the compiled version. I have had no errors when compiling, but the error comes up when I run it.
This is the function causing the problem:
string getString()
{
string wordInput;
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
while (wordInput.length() <= 3)
{
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
}
return 0;
}
The while loop isn't a problem. I commented it out and I still got the same error. How is initializing word input, cout, and getline giving me the error?
Here is my whole code so far (not finished). I tried running the string by itself too, the getKeyLetter function isn't a problem.
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
char getKeyLetter()
{
char keyLetter;
string convertFromString;
cout << "Enter a SINGLE character! ";
getline(cin, convertFromString);
while (convertFromString.length() > 1)
{
cout << "Enter a SINGLE character! ";
getline(cin, convertFromString);
}
assert(convertFromString.size() == 1);
keyLetter = convertFromString[0];
return 0;
}
string getString()
{
string wordInput;
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
while (wordInput.length() <= 3)
{
cout << "Enter a word that has AT LEAST four (4) letters! ";
getline(cin, wordInput);
}
return 0;
}
int main()
{
getKeyLetter();
getString();
return 0;
}
First, in your GetKeyChar() function, writing:
char ch;
cout << "Enter a single character: ";
cin >> ch;
will give you the first character the person types into the command prompt. So, typing "check" will have ch = c.
Second, as eran said, at the end of your functions, you have
return 0;
Unless you want both functions to return a char and string respectively, make them void GetKeyLetter() and void GetString(). Or, if you do want to return something, have them return ch (from my example) and return wordInput.
Only int main(), per standard, needs return 0, to show you that it exited correctly. the variable type you put in front of your functions is what variable you plan on returning. 0 is an int, so that's what it returns based on convention. As was pointed out, a return is not necessary in main. If you want your functions to return values, do this in your main.
string str;
char ch;
ch = GetKeyLetter();
str = GetString();
return 0;
And have your functions return the char and string value you want them to.
I'm trying to write a c++ program that tests each input integer, and stops if the input is invalid.
Here is my code, without the testing part:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
cin >> i;
cout << endl << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
How can I test the input for validity?
The easiest is to use std::getline to read a whole line of input into a std::string, and then test whether that string is a valid integer specification.
It's also possible to do this by testing the failure state of cin, and clearing it, but that way lies an assortment of complications that you don't want.
In order to test the string you can use a high level std::istringstream (just read from it and test its failure state after) or, more efficient but a little more complicated, strtol from the C library (the latter is what a C++ stream uses internally).
You need to test whether a string is an integer without crashing.
You can do this with strtol(). It converts the string to an integer, and reports on the first character that is not a legal char for a number. No invalid characters means the entire string was an integer.
There is a good description and example of how to use it here:
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int i;
do
{
cout << "\nPlease enter an integer: ";
while(!(cin >> i))
{
cin.clear();
cin.ignore();
cout << "\nInput was invalid, please re-enter: ";
}
cout << endl << "The integer is: " << i << endl;
} while(i != 0);
system("Pause");
return 0;
}
First post! This is my second semester with "Advanced C & C++" so any help is GREATLY appreciated. I've already scoured as much of stackoverflow and a few other resources to try and help me understand what I'm doing (or not doing) with this slew of logically inept code.
The goal of this program is to recognize whether or not a 'number' given by the user is a palindrome. Sounds simple enough right?! Ugh...well this is what I have been stuck on:
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
#include <cstdlib>
int main()
{
//variable declarations
string buffer;
//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}
The problem arises when input of "010", or "400" is given. "400" is essentially "00400" in this case and both should be seen as a palindrome.
A better approach would be to get trailing zeros for the given number as below:
int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;
Or the integer way as:
int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}
Now, check for the input string whether it has the same number of zeros befire the number or not as:
int counterZeros = 0;
while(str[counterZeros++]=='0');
check these 2 numbers and if trailing zeros are more than the zeros at beginning, add that many at the beginning and pass that string to palindrome function.
First of all, to recognize a palindrome, you don't have to do atoi. Just pass from the start to the middle checking if
buffer[i] == buffer[length - i]
Second, use the atoi to make sure it is a number and you're done.
Other way is to compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}
I'm just following a simple c++ tutorial on do/while loops and i seem to have copied exactly what was written in the tutorial but i'm not yielding the same results. This is my code:
int main()
{
int c=0;
int i=0;
int str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15);
cout << "The sum of the numbers are: " << c << endl;
system("pause");
return (0);
}
Right now, after 1 iteration, the loop just runs without asking for my inputs again and only calculating the sum with my first initial input for i.
However if i remove the second pair of cout/cin statements, the program works fine..
can someone spot my error please? thank you!
After you read the string with your cin >> str;, there's still a new-line sitting in the input buffer. When you execute cin >> i; in the next iteration, it reads the newline as if you just pressed enter without entering a number, so it doesn't wait for you to enter anything.
The usual cure is to put something like cin.ignore(100, '\n'); after you read the string. The 100 is more or less arbitrary -- it just limits the number of characters it'll skip.
If you change
int str;
to
char str;
Your loop works as you seem to intend (tested in Visual Studio 2010).
Although, you should also probably check for str == 'n', since they told you that they were done.
...and only calculating the sum with my first initial input for i...
This is an expected behavior, because you are just reading the str and not using it. If you enter i >= 15 then loop must break, otherwise continues.
I think you wanted this thing
In this case total sum c will be less than 15 and continue to sum if user inputs y.
#include<iostream>
using namespace std;
int main()
{
int c=0;
int i=0;
char str;
do
{
cout << "Enter a num: \n";
cin >> i;
c = c + i;
cout << "Do you wan't to enter another num? y/n: \n";
cin >> str;
} while (c < 15 && str=='y');
cout << "The sum of the numbers are: " << c << endl;
return 0;
}