How do I write a C++ code that accepts a rational number in one input?
ραλπθ
2010-09-25 14:30:37 UTC
I'm having trouble figuring this out. I can do it if the input can ask for the numerator and denominator separately but from my homework, we're supposed to only have one input for each rational number.
Three answers:
Silent
2010-09-25 14:41:24 UTC
I think the idea here is to get you to learn some string manipulation.
Ask the user to type the number in like this: 1/3
Get the result as a string. Then split it into two parts, using the position of the slash to determine where to split it. Parse each part into an int, and you've got your numerator and denominator.
cja
2010-09-25 16:14:20 UTC
The previous responder has the right idea, but I don't think it's as difficult as it might sound. Here's how I would do it:
#include
#include
#include
using namespace std;
float getRational(const string&, int *, int *);
const string prompt("Enter a rational number (x / y)");
int main(int argc, char *argv[]) {
float r;
int numerator, denominator;
while (true) {
r = getRational(prompt, &numerator, &denominator);
There are functions in string.h that are very handy for a problem like this. If you're not familiar with them (strtok, strpbrk, etc.), check your textbook or online resources and learn about them. I think your program should look something like this: #include #include #define MAX_LINE_LEN 1024 #define WS " \",:;-(){}[]<>/\\=+\t" #define END ".?!" char line[MAX_LINE_LEN]; char filename[MAX_LINE_LEN]; int main(int argc, char *argv[]) { FILE *fp; char *p; size_t wordCount = 0; printf("\nEnter filename: "); fgets(filename,MAX_LINE_LEN,stdin); *strchr(filename,'\n') = '\0'; if ((fp = fopen(filename,"r")) != NULL) { while (fgets(line,MAX_LINE_LEN,fp) != NULL) { *strchr(line,'\n') = '\0'; for (p = strtok(line,WS); p != NULL; p = strtok(NULL,WS),strpbrk(p,END)) { ++wordCount; } } printf("word count : %d\n",wordCount); fclose(fp); } else { printf("%s not found.",filename); } return 0; } #if 0 Sample run: Enter filename: text3.txt word count : 18 Where: $ cat text3.txt Just a week ago, drivers nationally paid about 17 cents less for a gallon of gas on average. Checking : $ wc text3.txt 2 18 94 text3.txt #endif
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.