I've been writing a simple data base in C++ using my basic object programming skills and I've come across a problem that I don't know how to get through. In one on my methods I'm trying to check correct forma of an input provided by a user. In order to achive that I need to know how long is the input string. Unfortunately an error pops out that the expression has to me modifiable l-value. I've searched for the answer, but I didn't really understand the solutions. Could you please, in layman terms, explain to me what did I do wrong?
Thank you!
The structure of the class I'm working with:
class Item
{
public:
void checkPNA()
{
if ((pna.length() = !6)||(pna[2]=!"-"))
{
cout<<endl<< "Niepoprawny format kody pocztowego! Poprawny format: \"00-000\". Spróbuj ponownie: ";
}
}
string nazwisko, imie, ulica, pna, miasto, attrib;
int id, len;
};
Simple syntax errors, it's != not = ! or =!, and it's '-' not "-" for a character.
if ((pna.length() = !6)||(pna[2]=!"-"))
should be
if ((pna.length() != 6) || (pna[2] != '-'))
You also don't need all those brackets
if (pna.length() != 6 || pna[2] != '-')
is easier to read in my opinion.
Related
I'll preface this by saying I'm relatively new to posting questions, as well as C++ in general, my title is a little lame as it doesn't really specifically address the problem I am dealing with, however I couldn't really think of another way to word it, so any suggestions on improving the title is appreciated.
I am working on a relatively simple function which is supposed to get a string using getline, and read the spaces and/or newlines in the string so that it can output how many words have been entered. After reaching the character 'q' it's basically supposed to stop reading in characters.
void ReadStdIn2() {
std::string userInput;
const char *inputArray = userInput.c_str();
int count = 0;
getline(std::cin, userInput, 'q');
for (int i = 0; i < strlen(inputArray); i++){
if ((inputArray[i] == ' ') || (inputArray[i] == '\n')){
count += 1;
}
}
std::cout << count << std::endl;
}
I want to be able to enter multiple words, followed by newlines, and have the function accurately display my number of words. I can't figure out why but for some reason after entering 3 newlines my count goes right back to 0.
For example, if I enter:
hello
jim
tim
q
the function works just fine, and returns 3 just like I expect it to. But if I enter
hello
jim
tim
bill
q
the count goes right to 0. I'm assuming this has something to do with my if statement but I'm really lost as to what is wrong, especially since it works fine up until the 3rd newline. Any help is appreciated
The behaviour of the program is undefined. Reading input into std::string potentially causes its capacity to increase. This causes pointers into the string to become invalid. Pointers such as inputArray. You then later attempt to read through the invalid pointer.
P.S. calculating the length of the string with std::strlen in every iteration of the loop is not a good idea. It is possible to get the size without calculation by using userInput.size().
To fix both issues, simply don't use inputArray. You don't need it:
for (int i = 0; i < userInput.size(); i++){
if ((userInput[i] == ' ') || (userInput[i] == '\n')){
...
I have a C++ test question that asks us to write a program that:
1) asks the user to input a string of answers a,b,c, and d: (Example: ACDBDA)
2) asks he user to input a string that is the answer key: (example DBADCD) (we also need to put in something to make sure the length of the answer key is the same as the answers, but that is no biggie)
3) prints the percentage of input answers that were correct, ie match up with the answer key.
Most of this isn't too bad, but I'm not sure how to go about comparing the two strings to see how they differ. Is there any way to get a variable equal to one of the characters in the string which could then be compared with a variable representing the character in the same place as the other string? That's the only way that comes to mind for me. I'm not really looking for a specific code or someone to do it for me, just need some pointers in the right direction.
Thanks!
Ok, so I've made some progress on this and I think I am close. The problem now is that I'm getting "Expression must be of class type" error on the commented lines. I think the issue is in the way I am passing my parameters but I can't seem to figure out how to fix it :(. I've google'd several parameter passing articles but none seem to speak to passing a parameter then getting it's length or comparing it as I do in the program. Any help would be greatly appreciated. Here is the code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
string getAnswers(string answers)
{
cout << "What are your answers to this questionless quiz? BE WARY OF CHOOSING INCORRECTLY\n:";
cin >> answers;
return answers;
}
string getKey(string key)
{
cout << "Just kidding. What are the answers? \n:";
cin >> key;
return key;
}
double getPercentage(double percentage)
{
int total;
int correct;
getAnswers();
getKey();
total = getAnswers.size(); // "error: expression must have class type"
for (i=0; i>total; i++)
{
int j = 0;
if (getAnswers.at(j) = getKey.at(j)) // "error: expression must have class type" (for both getAnswers and getKey)
correct++;
j++;
}
percentage = (correct/total) * 100;
}
int main()
{
getAnswers();
getKey();
cout << getPercentage(answers, key); //Also I'm really not sure how to get the parameters from previous functions into this one here. Maybe I shoudln't even add parameters and just show the function?
return 0;
}
This question already has answers here:
How to determine if a string is a number with C++?
(36 answers)
Closed 10 months ago.
Hi Can anyone help me please. I need to check that my input only contains integers. Im guessing from looking it up that I use the isDigit function but I am not sure how to use this to check the whole number.
I'm using C++ to interact with MSI so i'm getting the integer as follows:
hr = WcaGetProperty(L"LOCKTYPE",&szLockType);
ExitOnFailure(hr, "failed to get the Lock Type");
I think i have to change szLockType to a char and then use isdigit to scan through each character but i am not sure how to implement this. Any help would be greatly appreciated. P.s im a beginner so please excuse if this is a really trivial question..:)
Use std::stoi(). You'll get an exception if the string is not an integer value.
What's the type of szLockType?
Is it a a null-terminated char-string?
Then you can use the array syntax to get individual characters.
for(int i = 0; i < std::strlen(szLockType); i++) {
if(!std::isDigit(szLockType[i])) {
// it contains a non-digit - do what you have to do and then...
break; // ...to exit the for-loop
}
}
Or is it a std::string? Then the syntax is slightly different:
for(int i = 0; i < szLockType.length(); i++) {
if(!std::isDigit(szLockType.at(i)) {
// it contains a non-digit - do what you have to do and then...
break; // ...to exit the for-loop
}
}
Even better, with modern C++ you can do this:
#include <algorithm>
#include <cctype>
auto lambda = [](auto elem)
{
return std::isdigit(elem);
};
return std::all_of(szLockType, szLockType + strlen(szLockType), lambda);
Your choice as to whether you prefer a named lambda or regular, anonymous lambda.
FYI it is std::isdigit rather than isDigit.
https://en.cppreference.com/w/cpp/string/byte/isdigit
This is what I have:
char userInput;
int position;
vector<string> userVector(7);
vector<int> someVector(7,1);
cin >> userInput;
cin >> position;
if(userInput == 'X')
userVector[position] = '1';
if(userVector[position]-someVector[position] == 0)
cout << "Success"
My problem is that userVector[position] is actually a character, because userVector is a string vector. However, I need this calculation to take place (userVector[position] - someVector[position]) because I need to determine if the outcome is 0 or some other number. Any help?
In case it doesn't make sense here, userVector HAS to be a string vector, because it's part of the requirements for this program. Basically, a user is supposed to be allowed to enter an "X" anywhere in the userVector vector, and you have to tell them if it matches expected outputs.
So, in this case, the "expected output" would be someVector, which has a 1 in all of it's spaces. What I'm trying to do is subtract the two vectors so that if the user enters anything other than X, the vector subtraction will not equal 0, and consequently, result in the program doing something different.
Hope that clears things up!
If I understand correctly your code, you are trying to convert a string representing a decimal number into an integer. You have several ways of doing that; e.g., by using istringstream:
int num;
if (!(istringstream(userInput[position]) >> num))
num = 0;
if (n - someVector[position] == 0) {
...
or you could use good old atoi:
if (atoi(userInput[position].c_str()) - someVector[position] == 0) {
If I am wrong about what you are trying to do, please clarify what you are trying to do...
I can't figure out what you're trying to do from your statement of the
problem. The expression userInput[position] isn't legal, since
userInput isn't a pointer, nor anything that can be converted to a
pointer.
But your code doesn't seem to correspond to the textual description,
since you describe userInput as a string vector
(std::vector<std::string>?), but the code declares it as a char.
I am not good with c++ and I cannot find this anywhere, please apologize me if it is a bad question. I have a pointer and I want to know if some names store in this pointer begins with some specific string. As in python something like (maybe it is a bad example):
if 'Pre' in pointer_name:
This is what I have:
double t = 0;
for (size_t i =0; i < modules_.size(); ++i){
if(module_[i].name() == "pre"){ // here is what I want to introduce the condition
if (modules_[i].status() == 2){
std::cout << module_[i].name() << "exists" << std::endl;
}
}
}
The equivalent of Python 'Pre' in string_name is:
string_name.find("Pre") != std::string::npos // if using string
std::strstr(pointer_name, "Pre") // if using char*
The equivalent of Python string_name.startswith('Pre') ("begins with some specific string") is:
string_name.size() >= 3 && std::equal(string_name.begin(), string_name.begin() + 3, "Pre"); // if using string
string_name.find("Pre") == 0 // less efficient when it misses, but shorter
std::strncmp(pointer_name, "Pre", 3) == 0 // if using char*
In two of those cases, in practice, you might want to avoid using a literal 3 by measuring the string you're searching for.
Check std::string::find, there are enough good examples. If you are using c-style string, use strstr.
You can use the algorithm header file to do most of things usually one liners in python.
In this case though it might be just easier to use string find method .
If your name variable is of type std::string then you can use name().compare("Pre") == 0 for string comparison.
EDIT: Seems I misunderstood the question, for contains you can use string find, as other said.
Using C style strings, char * is not recommended in C++. They are error prone.