scanning a line has strings and integer C - string

I have a project and im facing a problem in this code
void Show() {
system("cls");
FILE *AddedSc;
int sc1i,sc2i;
int sc1ii,sc2ii;
char TNi[100],TN2i[100];
char TNii[100],TN2ii[100];
AddedSc = fopen("addedscores.txt", "r");
printf(" - Choose teams from this list: \n\n");
printf(" 1. Brazil\n 2. Germany\n 3. Italy\n 4. KSA\n 5. Portogual\n 6. Australia\n 7. USA\n 8. Spin\n 9. England\n 10. Korea\n\n\n");
printf(" * Enter the two teams that you want to show their results: ");
printf("\n\n\nTeam A: ");
scanf("%s", TNi);
printf("Team B: ");
scanf("%s", TN2i);
while (fscanf(AddedSc,"%[^\n] %d %d %[^\n]", TNii, sc1ii, sc2ii,TN2ii) !=EOF) {
if (strcmp(TNi, TNii) == 0 && strcmp(TN2i, TN2ii) == 0)
printf("\n\n%s %d - %d %s", TNi, sc1ii, sc2ii, TN2i);
else if(strcmp(TN2i, TNii) == 0 && strcmp(TNi, TN2ii) == 0)
printf("\n\n%s %d - %d %s", TN2i, sc2ii, sc1ii, TNi);
else printf("Not found!");
}
fclose(AddedSc);
there is a file contains data like this
usa 2 0 italy
I want the user to enter the name of two teams and let the program to search in the file and compare what the user entered and print the result of the match on the screen ..
please help me in this....

The problem is the first format, %[^\n], which will eat up all the lines in the input. You can change it just %s as follows:
while (fscanf(AddedSc,"%s %d %d %s", TNii, sc1ii, sc2ii,TN2ii) != EOF)
And it will be safer to compare the result as:
while (fscanf(AddedSc,"%s %d %d %s", TNii, sc1ii, sc2ii,TN2ii) == 4)

Related

How do i create an option in switch case?

I've recently tried to make some switch case function. Now, I'm currently trying to make an option but it seems it always skips the if part in case 1. The input just doesn't go in the if - else part.
#include <stdio.h>
int main(){
int option;
char choice;
int celcius;
menu:
printf("Welcome to program.\n");
printf("1. Input celcius\n");
printf("2. Convert To Kelvin\n");
printf("3. Convert To Fahrenheit\n");
printf("4. Convert To Reamur\n");
scanf("%d", &option);
switch(option){
case 1:
scanf("%d", &celcius);
printf("The value is : %d\n", celcius);
printf("Continue? : (y/n)\n"); scanf("%c", &choice);getchar();
if(choice == 'y' || choice == 'Y'){
goto menu;
}else if(choice == 'n' || choice == 'N');
break;
}
case 2:
printf("Please input the value: "); scanf("%d", &celcius);
int kelvin = celcius + 273;
printf("Converted Value is : %d\n", kelvin);
break;
case 3:
printf("Please input the value: "); scanf("%d", &celcius);
int fahrenheit = celcius + 32;
printf("Converted Value is : %d\n", fahrenheit);
break;
case 4:
printf("Please input the value: "); scanf("%d", &celcius);
int reamur = 5/4 * celcius;
printf("Converted Value is : %d\n", reamur);
break;
default:
printf("Wrong input.\n");
}
return 0;
}
(incomplete code because currently trying to make the case 1 works.)
Any solutions will help : )
You have a getchar() after the scanf() for choice. This is reading the newline character that is left in the input buffer after the scanf() for option.
You need to remove the getchar() and change the scanf() for choice to:
scanf(" %c", &choice);
The space before the %c will skip any whitespace characters in the input buffer.

I need to fix my code to count the syllables of multiple string inputs

As a new student to the C++ language I was originally given the assignment to write a code that would count the amount of syllables in a given string. Later it was changed on me to be able to count multiple strings.Now keep in mind I'm not to far along in the class and honestly I have my concerns about whether or not I'm actually learning what I need to pass this class. So I went back and started the frustrating process of changing my code when it already worked for a different function. I managed to produce the desired format of:
Word Syllable
Harry 2
Hairy 2
Hare 2
The 2
As you can tell it's not correct as it counts the syllables of only the first word and then applies it to the others. I tried changing it to a for loop but it didn't work so I went to a while loop and I got a somewhat better result:
Word Syllable
Harry 2
Word Syllable
Hare 1
So now it correctly counts the syllables but only of every other word instead of all and double prints the table header. Now even my cout command tells me it's ambiguous even though it still runs so I'm extra confused. I'm thinking I might have to change it into an array but at this point I'm completely stumped.
Here is my code so far:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
cout << "Please enter four words: ";
string word;
while (cin >> word);
{
cin >> word;
bool last_vowel = false;
bool last_cons = false;
bool curr_vowel = false;
bool curr_cons = false;
int syllable_count = 0;
for (int i = 0; i < word.length(); i++)
{
string letter = word.substr(i, 1);
if (letter == "a" || letter == "e" ||
letter == "i" || letter == "o" ||
letter == "u" || letter == "y" ||
letter == "A" || letter == "E" ||
letter == "I" || letter == "O" ||
letter == "U" || letter == "Y")
{
curr_vowel = true;
curr_cons = false;
}
else
{
curr_vowel = false;
curr_cons = true;
}
// Increment the syllable count any time we
// transition from a vowel to a consonant
if (curr_cons && last_vowel)
{
syllable_count++;
}
last_vowel = curr_vowel;
last_cons = curr_cons;
}
// Check the last letter in word.
string last = word.substr(word.length() - 1, 1);
// Add one for an ending vowel that is not an "e"
if (last == "a" || last == "i" || last == "o" ||
last == "u" || last == "y" || last == "A" ||
last == "I" || last == "O" || last == "U" ||
last == "Y")
{
syllable_count++;
}
// There has to be at least one syllable
if (syllable_count == 0)
{
syllable_count = 1;
}
cout << left;
cout << setw(10) << "Word" << setw(20) << "Syllables" << endl;
cout << "__________________________" << endl;
cout << left;
cout << setw(19) << word << syllable_count << endl;
}
return 0;
}
Tony answer to your problem is very complicated. I saw someone writing this looks like an unbelievably difficult problem in linguistics while researching the conditions of syllables.
I was not able to find any hard-set rule that can tell you how many syllables are there in the word.
I found some conditions on the program and checked the result to the code on this online tool https://syllablecounter.net/count my guess is they have some list of words to exclude from counting or to be included even if they do not fall under basic conditions.
Wrote the below code to count the syllables in each word of the given phrase.
The program will continue to ask for phrase, Till you enter something other then y when asked to continue.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
while (true) {
cout << "Enter the string you want to count syllable for: ";
string phrase, word;
string vowels = "aeiou";
getline(cin, phrase);
//cout << phrase << endl;
stringstream X(phrase); // Object of stringstream that references the phrase string
// iterate on the words of phrase
while (getline(X, word, ' ')) {
// logic to find syllable in the word.
// Traverse the string
int syllable_count = 0;
// if word[0] in vowels count as syllable
if(vowels.find(tolower(word[0])) != std::string::npos)
syllable_count +=1;
// if word[index] in vowels and word[index - 1] not in vowels count as syllable
for (int i = 1; i < word.size(); i++) {
if(vowels.find(tolower(word[i])) != std::string::npos && vowels.find(tolower(word[i-1])) == std::string::npos)
syllable_count +=1;
}
// if word ends with 'e' it does not cout as syllable
if(tolower(word[word.size()-1]) == 'e')
syllable_count -=1;
// if word ends with 'le' and not of 2 char only and last 3rd word not in vowels it count as syllable
if((word.size() > 2) && (tolower(word[word.size()-1]) == 'e' && tolower(word[word.size()-2]) == 'l' ) && vowels.find(tolower(word[word.size()-3])) == std::string::npos)
syllable_count +=1;
// if word end with 'y' treet it as syllable
if(tolower(word[word.size()-1]) == 'y'){
syllable_count +=1;
// if word end with 'y' and have vowel in last second position count both char as one syllable.
if((word.size() > 2) && vowels.find(tolower(word[word.size()-2])) != std::string::npos)
syllable_count -=1;
}
if(syllable_count == 0)
syllable_count += 1;
cout << word << " : " << syllable_count << endl; // print word and syllable cout
}
cout << "Press y if you want to continue: ";
string stop;
getline(cin, stop);
if( stop != "y")
return 0;
}
return 0;
}
Sample result
Enter the string you want to count syllable for: troy
troy : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: test
test : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: hi how are you
hi : 1
how : 1
are : 1
you : 1
Press y if you want to continue: y
Enter the string you want to count syllable for: Harry hairy hare the
Harry : 2
hairy : 2
hare : 1
the : 1
Press y if you want to continue: n
You might need to add some conditions as you find certain cases. This problem is not something that can be worked with if else only.
Hope this helps.

In C gets function is not working in iteration

At first do while iteration in my code, the gets() function works fine, but from the next iteration it skips the gets() function and moves on to the following statement.
So please anyone sort out the problem with a solution. The problem part will be highlighted in bold. The code is as follows:
void main()
{
char string[150], cont[5];
int total = 0, alpha = 0, digit = 0, spl_char = 0, upp = 0, low = 0;
int i, vowels = 0,consonants = 0;
int choice;
do
{
system("cls");
printf("\t\t\t\tSTRING OPERATIONS\n");
printf("\t\t\t\t~~~~~~ ~~~~~~~~~~\n");
printf("\nEnter the String: ");
***gets(string);*** // the problem part
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("1");
break;
case 2:
printf("2);
break;
default:
printf("\nSorry! The Entered Choice is Not Available. Try Again!");
break;
}
do
{
printf("\nDo you want to Continue (yes/no): ");
scanf("%s", cont);
if (stricmp(cont, "yes") == 0 || stricmp(cont, "no") == 0)
break;
printf("\nError!!! Please type only yes or no.\n");
} while(stricmp(cont, "yes") != 0 || stricmp(cont, "no") != 0);
} while(stricmp(cont, "yes") == 0);
}
The first iteration it asks & waits for the input:
for eg:
Enter the String: bat
and the process continues....
And in second iteration it just asks and skips to following statement:
for eg:
Enter the String:
Enter your choice:

How to read parts [duplicate]

This question already has answers here:
Why is “while( !feof(file) )” always wrong?
(5 answers)
Closed 2 years ago.
I have a problem with this program: I was able to make another draft program but it only reads the first three lines and stops. Unfortunately, the input file is not symmetrical so I should use while loops for some parts only to avoid repeating parts of the program. With strcpy I could copy the work done up to a certain point and then continue from that point on. I was trying but visual studio tells me to move the memory to the heap but I don't know how to do it ... Practically I should only extrapolate certain data from the input file and order them in an output file according to a precise line.
I also know there's a problemi with char buf[200], rec[200] because I have to allocate much more memory...
the first time in
while ( !feof(fd) ) {
fscanf(fd, "session %d (COPY MODE):\n\n", &session);
you call feof before any read so feof cannot work proprely, an easy change is to do
while (fscanf(fd, "session %d (COPY MODE):\n\n", &session) == 1) {
Out of that the mode can be something else that COPY MODE and the two \n after are not mandatory, you also do not check your next fscanf success and globaly the algorithm you use is wrong
A possible way to do the job also checking the validity of the input file is :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE * fp = fopen("summary.txt", "r");
if (fp == NULL) {
perror("cannot open summary.txt");
exit(1);
}
int session;
char mode[64];
const char * separator = "_____________________________________________";
while (fscanf(fp, " session %d (%[^)]):", &session, mode) == 2) {
if (strcmp(mode, "COPY MODE") && strcmp(mode,"ONLINE FREE MODE"))
{
fprintf(stderr, "invalid file, invalid mode '%s'\n", mode);
exit(1);
}
char line[64];
char given[64];
char recognized[64];
int registration, registration_set = 0;
int sequences, sequences_set = 0;
for(;;) {
/* read next line, bypass possible newline(s) before */
if (fscanf(fp, " %63[^\n]", line) != 1) {
if (!feof(fp)) {
perror("reading file");
exit(1);
}
*line = 0;
}
else if (sscanf(line, "number of sequences: %d", &sequences) == 1) {
sequences_set = 1;
continue;
}
else if ((*given == 0) &&
(sscanf(line, "characters given: %63s", given) == 1)) {
if (!registration_set) {
fprintf(stderr,
"registration is missing before 'characters given: %s'\n",
given);
exit(1);
}
if (!sequences_set) {
fprintf(stderr,
"sequences is missing before 'characters given: %s'\n",
given);
exit(1);
}
continue;
}
else if ((*recognized == 0) &&
(sscanf(line, "characters recognized: %63s", recognized) == 1)) {
if (!*given) {
fprintf(stderr,
"given is missing before 'characters recognized: %s'\n",
recognized);
exit(1);
}
continue;
}
if (registration_set) {
if (!*given) {
fputs("invalid file, given is missing\n", stderr);
exit(1);
}
printf("%d %d %d %s %s\n", session, registration, sequences, given, recognized);
if (!*line || !strcmp(line, separator))
break;
}
if (sscanf(line, "registration %d:", &registration) != 1) {
fprintf(stderr,
"invalid file, 'registration <n>:' expected rather than '%s'\n",
line);
exit(1);
}
else {
registration_set = 1;
*given = *recognized = 0;
}
}
}
fclose(fp);
return 0;
}
Note the space at the beginning of the format of the fscanf, that allows to bypass character considered to be space including the newline
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -Wall c.c
pi#raspberrypi:/tmp $ cat summary.txt
session 1 (COPY MODE):
number of sequences: 15
registration 1:
characters given: CALOR
registration 2:
characters given: CARINO
registration 3:
characters given: SUSHI
_____________________________________________
session 2 (COPY MODE):
registration 1:
number of sequences: 15
characters given: SUSHI
characters recognized: SUSHI
_____________________________________________
session 3 (ONLINE FREE MODE):
number of sequences: 15
registration 1:
characters given: PERA
characters recognized: PFRA
registration 2:
characters given: SALON
characters recognized: SALON
registration 3:
characters given: PERRO
characters recognized: PERRO
_____________________________________________
session 4 (ONLINE FREE MODE):
registration 1:
number of sequences: 7
characters given: TORTUGA
characters recognized: TORTUGA
registration 2:
number of sequences: 4
characters given: ANAEROBIO
characters recognized: ANAERPBIO
registration 3:
number of sequences: 4
characters given: PAPELES
characters recognized: PAPELEX
pi#raspberrypi:/tmp $ ./a.out
1 1 15 CALOR
1 2 15 CARINO
1 3 15 SUSHI
2 1 15 SUSHI SUSHI
3 1 15 PERA PFRA
3 2 15 SALON SALON
3 3 15 PERRO PERRO
4 1 7 TORTUGA TORTUGA
4 2 4 ANAEROBIO ANAERPBIO
4 3 4 PAPELES PAPELEX
pi#raspberrypi:/tmp $

linux terminal output

Hi I wrote a simple c prog to just accept a password while diplaying * to hide the input. But the * for the last character entered is not appearing at the right place.
the code is below
int main(){
int choice = 0;
char pass[8];
FILE *input;
FILE *output;
struct termios initial_settings, new_settings;
if(!isatty(fileno(stdout))){
fprintf(stderr,"Not a terminal \n");
}
input = fopen("/dev/tty","r");
output = fopen("/dev/tty","w");
if(!input || !output){
fprintf(stderr,"error opening");
exit(1);
}
tcgetattr(fileno(input),&initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
new_settings.c_cc[VMIN] = 1;
new_settings.c_cc[VTIME] = 0;
new_settings.c_lflag &= ~ISIG;
if(tcsetattr(fileno(input), TCSANOW, &new_settings) != 0) {
fprintf(stderr,"could not set attributes\n");
}
int count = 0;
char ch;
printf("Please enter the password: ");
while (count<8){
ch = fgetc(input);
if(ch == '\n' || ch == '\r'){
break;
}else{
fputc('*',stdout);
pass[count] = ch;
count++;
}
tcdrain(fileno(stdout));
}
fprintf(output,"you have entered :%s \n",pass);
tcsetattr(fileno(input),TCSANOW,&initial_settings);
exit(0);
}
The output is as follows:
Please enter the password:* * * * * * *
you have entered :12345678
* pasman#pasman-laptop:~$
Its an 8 character password & Notice that 7 *s appear as expected but the last * is appearing at the end of main.
You're mixing stdio and another stream, output, talking directly to the tty. They have different buffers, and get flushed at different times. You really should just use one of them.
It's because you break before you write the last *: so
add
fputc('*',stdout);
before
tcdrain(fileno(stdout));

Resources