The program should print the number of empty lines and certain operators from the input text. I got the problem of empty lines fixed but I'm facing issues with the opperators. I guess it is something wrong with the break. I would appreciate any good ideas for fixing the code. Sorry if such a thread already exists but I checked and couldn't get a solution. Thanks in advance!
char c,line[300];
int emptyLine = 0;
int operators = 0;
printf("Input your text and press ctr+Z on a new line when done: \n");
while(gets(line)) {
int i = 0;emptyLine++;
for (i = 0; i < strlen(line); i++) {
if(line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%')
{
operators++;
}
if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') {
emptyLine--;
break;
}
}
}
printf("The number of empty lines is: %d",emptyLine);
printf("\nThe number of opperators is: %d",operators);
Try something like this:
char c,line[300];
int emptyLine = 0;
int operators = 0;
printf("Input your text and press ctr+Z on a new line when done: \n");
while(gets(line)) {
bool isEmpty = true; // Assume empty line
for (int i = 0; 0 != line[i]; i++) {
if (!isspace(line[i])) {
isEmpty = false; // Line not empty
}
if (line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%') {
operators++;
}
}
if (isEmpty) {
emptyLine += 1;
}
}
printf("The number of empty lines is: %d",emptyLine);
printf("\nThe number of operators is: %d",operators);
Related
I am getting an int of the entire string s for 'letter', the conditions in my 'if' statement seem to not be reading properly - is my syntax incorrect?
I get user input:
string s = get_string("Text here: ");
the function is as follows:
int letter_count(string s)
{
int i =0;
int len = strlen(s);
int letter = 0;
while(i < len)
{
if (s[i] != '\0' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
then call the function:
int letter = letter_count(s);
printf("letter Count: %i\n", letter);
Try changing the OR operator with the AND
if (s[i] != '\0' || s[i] != '.' || s[i] != ',' || s[i] != '!' || s[i] != '?')
is ALWAYS true. Because any character is either not "." or not ",". Which letter would you expect to be both?
You want to check whether the current letter is "not ." AND "not ," AND "not !".
I.e.
if (s[i] != '\0' && s[i] != '.' && s[i] != ',' && s[i] != '!' && s[i] != '?')
Almost correct, you have to change the type of the argument to char*, there is no string type on the default libraries. (Documentation of string library).
Working example with the modifications:
#include <stdio.h>
#include <string.h>
int letter_count (char* s)
{
int i = 0;
int len = strlen (s);
int letter = 0;
while (i < len)
{
if (s[i] != '\0' && s[i] != '.' && s[i] != ',' && s[i] != '!'
&& s[i] != '?')
{
letter++;
}
i++;
}
return letter;
}
int main ()
{
char my_word[] = "Sample word";
printf ("'%s' have %d letters",my_word, letter_count (my_word));
return 0;
}
Output:
'Sample word' have 11 letters
I am working on a question which requires me to print a string given a field-number at that position. The strings should be read from a file.
file.txt
C is a language.
lex lexical analyser
(blank line)
gcc is good
If the field-number is 2 (i.e the second word in the sentence). The program should output
is
lexical
(NULL)
is
I wrote a function but don't think its the correct way and that it would work for all cases. It should handle extra blanks or newlines.
while (fgets(buffer, MAX, file) != NULL) {
for (int i = 1; i < strlen(buffer); i++) {
if (count == field_number - 1) {
int j = i;
while (j < strlen(buffer) && buffer[j] != ' ') {
printf("%c", buffer[j++]);
}
printf("\n");
count = 0;
break;
}
if (buffer[i] == ' ' && buffer[i - 1] != ' ') {
count++;
}
}
}
I am a beginner. This code should be easy to understand.
This should work for all the cases,
int main() {
//FILE* file = fopen(__FILE__, "r");
//int field_number = 2;
int new_line = 0; // var to keep track of new line came or not
int word = 0;
int count = 0;
char c, prev_c;
while ((c = fgetc(file)) != EOF) {
// printf("[%c]", c);
// if a new line char comes it means you entered a new line
if(c == '\n') {
// you have to print the new line here on the output to handle
// empty line cases
printf("\n");
new_line = 1; // when line changes
word = 0; // no word has come in this new line so far
count = 0; // count becomes 0
} else if( c == ' ' && prev_c != ' ') {
if(word)
count++;
if(count == field_number) // if count exceeds field_number
new_line = 0; // wait till next line comes
} else if (new_line && count == field_number - 1) {
printf("%c", c);
} else {
word = 1; // fi a not new line or non space char comes, a word has come
}
prev_c = c;
}
return 0;
}
I'm probably implementing this code in a terrible way, but i'm currently doing CS50 and trying to search my string for the char '. I searched for other chars such as text [i] == '!' however when doing text [i] == ''' it doesn't work correctly. Is it possible to make it work in this way?
Here's my terrible code if your interested... i'm trying to find the number of letters, words, and sentences.. it works other than the characters i can't define.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main (void)
{
string text = get_string("Input text: "); //accept text input
int i;
int length = strlen(text);
int count = 0;
int count2 = 0;
int count3 = 0;
int excludeothers = (length - count);
for (i = 0; i < length; i++)
{
if(text[i] == ' ' || text [i] == '!' || text[i] == '?' || text[i] == '.' || text[i] == ',' || text[i] == '"' || text[i] == ':' || text[i] == ';' || text[i] == '-' || text[i] == ''') //check number of letters
{
count++;
}
}
for (i = 0; i <= length; i++)
{
if((text[i] == ' ' || text[i] == '\0') && (text[i-1] != ' ' || text[i-1] != '\0')) //check number of words
{
count2++;
}
}
for (i = 0; i < length; i++)
{
if((text[i] == '.' || text[i] == '?' || text [i] == '!') && (text[i+1] == ' ' || text[i+1] == '\0')) //check number of sentences
{
count3++;
}
}
printf("%i letters\n", excludeothers); //print letters
printf("%i words\n", count2); //print words
printf("%i sentences\n", count3); //print sentences
}
You need to escape it:
'\''
This means the single quote char. Same way you can have double quote in a string: "\""
Further reading: https://en.wikipedia.org/wiki/Escape_sequences_in_C
If you want to do it your way, then, yes, you need to escape that character. Take a look at GeeksForGeeks article about escaping characters in general. It will help you knowing which ones can be passed as normal characters and which ones will need a backslash in front of them.
However, if you are considering other options, take a look at strchr(). It is a builtin function that you can use. Using this will drastically improve and simplify your code. You can take a look at this question discussion for more information. And here is a reference for C documentation on this function.
I am trying to write a program that checks to see if a word inputed to a program matches one of the predefined keywords. Input is going to be coming from a text file and the text file will have a single word in it. So far the text file I have just has the word 'frog' which means the program should clearly print 'No Match Found' but it in fact prints 'Match Found' It prints prints 'Match Found' even when the word in the text file is a string of random letters. Here is my code, does anything stand out to you guys? Thanks
#define NUM 4
#define SIZE 12
int isAlpha(char);
//Returns 1 if it is an Alphabetical character, 0 if it is not
int isAlpha(char c) {
return (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z');
}
int main() {
char message[141];
int charCount = 0, c = 0, matchCheck = 0;
char keywords[NUM][SIZE] = {
"crackerjack",
"Hey",
"dog",
"feet"
};
//Removes non alphabetical characters
while((c = getchar()) != EOF && charCount <= 140) {
if(isAlpha(c)){
message[charCount] = c;
charCount++;
}
}
//checks if message matches keyword
for (int i = 0; i < NUM; i++) {
for (int j = 0; j < SIZE; j++) {
//Check if current two characters match
if (message[j] == keywords[i][j]) {
//Check if the two matched characters are the null terminator character
if (message[j] == '\0' && keywords[i][j] == '\0') {
matchCheck = 1;
break;
}
}
}
}
//prints "Match Found!" if there was a match
if (matchCheck == 1)
printf("Match Found!\n");
else
printf("No Match Found\n");
}
I havent programmed in C in a long time, and I dont have a C compiler with me right now. However, I think that there might be a problem with the logic. You need to check for every word individually. I would do somehting like the following for your last section ...
matchAnyWord = 0
for (int i = 0; i < NUM; i++) {
matchCheck = 1;
for (int j = 0; j < SIZE; j++) {
if (message[j] == '\0' && keywords[i][j] == '\0') break;
if (message[j] == '\0' && keywords[i][j] != '\0') { matchCheck = 0; break;}
if (message[j] != '\0' && keywords[i][j] == '\0') { matchCheck = 0; break;}
if (message[j] != keywords[i][j] ) { matchCheck = 0; break;}
}
if (matchCheck == 1) {matchAnyWord = 1; break;}
}
Note that here we check for the matching of individual words, and introduce a new variable matchAnyWord which is actually what you want. I might have errors in the syntax but I think the logic should be more-or-less there.
Cheers!
Also, not sure why the indentation isnt showing up correctly on my browser ...
I am trying to remove all quotes in a given line except a backslash followed by a quote
what I have done is this
for (int i = 0; i < lineLength; i ++) {
if (line[i] == '"' ) {
if (line[i-1] == '\\') // if \" is used
line[i-1] = '"'; // then print \
line[i] = '\0'; // or 0
}
}
This removes all characters in the line.. what can I do to remove only quotes?
Any help would be appreciated...
Your problem is line[i] = '\0'; - it terminates the string.
If you want to remove characters from a C string, you need to hold two indices - one for reading and one for writing, loop over the read index reading each character, and write only the ones you want to keep using the second index.
Something along the lines of:
int j = 0;
for (int i = 0; i < lineLength; i ++) {
if (line[i] != '"' && line[i] != '\\') {
line[j++] = line[i];
} else if (line[i+1] == '"' && line[i] == '\\') {
line[j++] = '"';
} else if (line[i+1] != '"' && line[i] == '\\') {
line[j++] = '\\';
}
}
//You missed the string termination ;)
if(j>0) line[j]=0;
You are setting the first " character you find to the null character, terminating the string.
Also an aside, but line[i-1] could cause a segmentation fault when i == 0, or it could happen to contain \ in which case the first quote wouldn't be stripped.
Something like this will do what you want:
char *lineWithoutQuotes = malloc(strlen(line));
int i, j;
if(line[0] != '"')
lineWithoutQuotes[0] = line[0];
for(i = j = 1; i < strlen(line); i++){
if(line[i] == '"' && line[i-1] != '\\')
continue;
lineWithoutQuotes[j++] = line[i];
}
The normal technique using indexes is:
int j = 0;
for (int i = 0; i < lineLength; i++)
{
if (line[i] == '\\')
{
line[j++] = line[i++];
line[j++] = line[i];
if (line[i] == '\0')
break;
}
else if (line[i] != '"')
line[j++] = line[i];
}
line[j] = '\0';
Using pointers (and not needing lineLength), it is:
char *dst = line;
char *src = line;
char c;
while ((c = *src++) != '\0')
{
if (c == '\\')
{
*dst++ = c;
if ((c = *src++) == '\0')
break;
*dst++ = c;
}
else if (c != '"')
*dst++ = c;
}
*dst = '\0';
Or minor variations on those themes...
int newPos = 0;
for (int oldPos = 0; oldPos < lineLength; oldPos++) {
if (!(line[newPos] == '"' && (!newPos || line[newPos-1] == '\\'))) {
line[newPos] = line[oldPos];
newPos++;
}
}
line[newPos] = 0;