Character operations in C++

Joined
Dec 12, 2022
Messages
8
Reaction score
0
The prompt is: "Read a 3-character string from input into variable inString. Declare a Boolean variable noDigits and assign noDigits with true if inString does not contain any digits. Otherwise, assign noDigits with false."
I cannot figure out why my code doesn't work. Any help would be appreciated!

C++:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
   string inString;
  
   getline(cin, inString);
   bool noDigits;
  
   if(!(isdigit(inString.at(0) && (!(isdigit(inString.at(1)) {
      noDigits = true;
   } else {
      noDigits = false;
   }
  
   if (noDigits) {
      cout << "String accepted" << endl;
   }
   else {
      cout << "String not accepted" << endl;
   }

   return 0;
}
 
Joined
Sep 3, 2023
Messages
36
Reaction score
2
Homework question? Hint the first compiler error I get is:

Code:
digit.cpp:19:62: error: expected ')'
   if(!(isdigit(inString.at(0) && (!(isdigit(inString.at(1)) {

This error is probably the number one programming nuisance.

Also use comments to comment out code to simplify the code. You need to have it compile properly before you can go on to fix other problems such as requirements.
 
Joined
Jul 4, 2023
Messages
478
Reaction score
60
Fix the condition in the first if statement to have the correct number of closing braces.
From this
C++:
if(!(isdigit(inString.at(0) && (!(isdigit(inString.at(1))
To for example
C++:
if (!isdigit(inString.at(0)) && !isdigit(inString.at(1)))



BTW check this
[ working code on-line ]
C++:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
   string inString;
 
   cout << "Enter a 3-character: ";
   getline(cin, inString);
  
   bool noDigits = true;
 
   for (char ch : inString) {
      if (isdigit(ch)) {
         noDigits = false;
         break; // Exit the loop early if a digit is found
      }
   }
 
   if (noDigits) {
      cout << "String accepted" << endl;
   } else {
      cout << "String not accepted" << endl;
   }

   return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,795
Latest member
YolandaCar

Latest Threads

Top