简体   繁体   中英

How do I convert a text string to an int in C to find parts in it?

My current issue with this code has to do with the Punctuation Count if statement if(Text == '.' || Text == '?' || Text == '?') .

Is there a variable I can create to replace Text in this situation and allow the code to run its process?

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>


int main(void)
{  //Letter Count Section
string Text = get_string("Text: "); //Gets Text
char Checker = isalpha(Text); // Checks for letters
int Count = strlen(&Checker); //Counts letters

//Space Count Section
 int Spaces = 0; //Declares Variable
if(isspace(Text)){ //Checks for Spaces
 Spaces += 1; //Adds +1 to Variable if Space
}

//Punctuation Count
 if(Text == '.' || Text == '!' || Text == '?')
 Punctuation += 1;

float Sentence = (Count/(Spaces*100));
float Letters = (Punctuation/(Spaces*100));
 printf("\n%f",Sentence);
 printf("\n%f",Letters);

 // Formula  
    int gradelvl = (0.0588 * Letters - 0.296 * Sentence - 15.8);
 // End Result  
        printf("\nGradelevel: %i\n",gradelvl);
}

Is there a variable I can create to replace Text in this situation and allow the code to run its process?

  char c = Text[0];

A C string is basically just an array of char values. Eg the following two definitions are both valid:

char * stringAsPtr = "Hello World";
char stringAsArray[] = "Hello World";

Thus you can process any string as an array:

for (size_t i = 0; stringAsArray[i]; i++) {
    char c = stringAsArray[i];
    // Do something with c, e.g. check if it is a space 
    // and increase your space counter if it is.
}

Note that stringAsArray[i] as a boolean expression is identical to stringAsArray[i] != 0 and to stringAsArray[i] != '\0' , so the for loop will end once you hit the terminating NUL character of the C string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM