I'm trying to write a program that counts all the characters in a string. I originally had it, but then realized I can't count spaces. I can't see why this does not work.
for(m=0; z[m] != 0; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
Any assistance appreciated.
Edit* Does it make a difference if the input(strings) are being scanned in like this? And yes, everything is initialized. I've tried printing what z[m] evaluates too and it isn't the actual value of the string at "m", I think this is the problem.
for(j=0; j<7; j++){
printf("Enter a string:\n");
scanf("%s", z);
for(m=0; z[m] != 0; m++){
if(z[m] != ' '){
charcount ++;
}
}
You need to initialize charcount. Other than that, it should work, provided that z is a zero-terminated array of characters and m is an int or similar. I would probably write just z[m] rather than z[m] != 0 (since !0 = true and 0 = false), but both work. There are more efficient ways of doing it (although these days I bet a compiler will handle converting this into a pointer-based loop for you).
Here's a complete, correct example with minimal edits:
const char * z = "testing one two three";
int m;
int charcount;
charcount = 0;
for(m=0; z[m]; m++) {
if(z[m] != ' ') {
charcount ++;
}
}
If you're using a String class of some kind rather than an old-fashioned C null-terminated array, you'll want to look at that class for how to loop through it.
All of the above also assumes you're dealing with ASCII strings. If you're dealing with UTF-encoded strings, you have to handle multi-byte characters.
Re your edit: It makes a big difference: scanf will stop on the first blank (I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring z correctly. (I'd also recommend using a field width when using scanf for reading strings [or avoiding scanf entirely]; otherwise, you have no control over the number of chars it will try to store, and so in theory, no buffer will ever be big enough to avoid an overflow. More here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)
You can use strlen()
I'd suggest using a while loop, and to use more meaningful variable names
m = textIndex
z = text
Something like this would work
while (text[textIndex] != 0x00)
{
textIndex++;
}
Instead of using scanf, try fgets like so:
char input[256];
fgets(input, sizeof(input), stdin);
fgets will read an entire line from a file. As such, passing stdin as the file handle will make it read from standard input, which in most cases will be bound to the console. One thing to watch out for, though, is that the string you get from fgets might include the newline character. Rather than explicitly checking your strings for inequality with the space character (' '), I suggest using the isspace function from ctype.h, which will check for various forms of whitespace (including a regular space and newline).
Here is a complete, runnable example:
#include <stdio.h>
#include <ctype.h>
int count_nonspace(const char* str)
{
int count = 0;
while(*str)
{
if(!isspace(*str++))
count++;
}
return count;
}
int main()
{
char input[256];
fgets(input, sizeof(input), stdin);
printf("%d\n", count_nonspace(input));
}
Yes, there is a difference on input-scan with scanf:
scanf("%s", z);
...
if(z[m] != ' '){
scanf("%s"...) always breaks at space-character, therefore your if ever is true. Better you use fgets to read from stdin,
#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
printf("Enter a string:\n");
if( fgets( line, 80, stdin ) )
{
char *c=line;
if( strchr(line,'\n') ) *strchr(line,'\n')=0;
while( *c )
{
if( *c!=' ' )
++charcount;
++c;
}
}
}
Or if you want WHITE -spaces then take
#include <ctype.h>
...
if( !isspace(*c) )
this seems to work for me, its a simple 30 line code that is in a loop and can detect the letter of choice for the chosen string/sentence/word the user has inputted.
#include <stdio.h>
#include <string.h>
int main(){
while(true){
char string[100];
char letter[100];
int count = 0;
printf("Enter a word/sentence:\n");
scanf(" %[^\n]s",string);
printf("Enter a letter:\n");
scanf(" %c",&letter); //when using scanf for a sentence/word or character, always include a space afterwards.
//Counts each character except space
for(int i = 0; i < strlen(string); i++) {
if(string[i] == letter[0]){
count++;
}
}
//Displays the total number of characters present in the given string
printf("Total number of characters in the string: %d\n", count);
printf("%s\n",string);
}
return 0;
}
Related
I'm a beginner programmer and im trying to solve some exercises and i needed some help with one of them.
The exercise goes like this:
We need to input a string of characters , read it and print out the length of each word.
This is what i did
int main()
{
char str[N+1+1];
int i=0;
int pos=0;
int wordlen=0;
int word[60]={0,};
printf("Please enter the string of characters: ");
gets(str);
while(i<strlen(str))
{
if(!isalpha(str[i]))
{
wordlen=0;
i++;
}
if(isalpha(str[i]))
{
wordlen++;
i++;
pos=i;
}
word[pos]=wordlen;
wordlen=0;;
i++;
}
for(i=0;i<20;i++)
{
if(word[i]==0) // here im just trying to find a way to avoid printing 0's but you can ignore it if you want
{break;}
else
printf("%d ",word[i]);
}
return 0;
}
The problem is that when i try to compile it for example: I input "hi hi hi" its supposed to print 2 2 2 but instead it's printing nothing.
Can i ask for some help?
I failed to follow OP's logic.
Perhaps begin again?
End-of-word
To "count the length of each word", code needs to identify the end of a word and when to print.
Detecting a non-letter and the current word length > 0 indicates the prior character was the end of a word. Note that every C string ends with a non-letter: '\0', so let us iterate on that too to insure loop ends on a final non-letter.
int word_length = 0;
int strlength = strlen(str); // Call strlen() only once
while (i <= strlength) {
if (isalpha(s[i])) {
word_length++;
} else {
if (word_length > 0) {
printf("%d ", word_length);
word_length = 0;
}
}
}
printf("\n");
gets()
gets() is no longer in the C library for 10 years as it is prone to over-run. Do not use it.
we are supposed to use gets. is unfortunate and implies OP’s instruction is out-of-date. Instead, research fgets() and maybe better instruction material.
Advanced
is...() better called as isalpha((unsigned char) s[i]) to handle s[i] < 0.
In general, better to use size_t than int for string sizing and indexing as the length may exceed INT_MAX. That is not likely to happen with OP's testing here.
I'm completely new to programming (1st term in uni) and I can't keep up with my lecturer. At the moment I'm stuck on this exercise (for much more time than I'm willing to admit). I've tried to find help on the internet (in this site and others as well), but I can't, since our lecturer has us use a very simple form of c. I'm not asking necessarily for a complete answer. I'd really appreaciate even some hints about where I'm on the wrong. I understand that it might be really simple for some, that the question might seem ignorant or stupid and I feel bad for not getting what's wrong, but I need to try to understand.
So, what I'm trying to do is use scanf and a do while loop so the user can input characters in an array. But I don't understand why the loop won't stop when the user presses ENTER. There's more to the code, but I'm trying to take it slowly, step by step. (I'm not allowed to use pointers and getchar etc).
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<=50) && (a[i-1]!='\0'));
for(i=0; i<50; i++)
printf("%c", a[i]);
}
There aren't any nul-terminated strings here, but only string arrays.
So, when pressing enter, a[i-1] is \n not \0 (scanf with %c as parameter doesn't nul-terminate the strings, and ENTER is just a non-nul character with code 10 AKA \n)
Then don't print the rest of the string because you'll get junk, just reuse i when printing the string back:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do
{
scanf("%c", &a[i]);
i=i+1;
}
while((i<sizeof(a)) && (a[i-1]!='\n')); // \n not \0
int j;
for(j=0; j<i; j++) // stop at i
printf("%c", a[j]); // output is flushed when \n is printed
}
Also test with i<50 not i<=50 because a[50] is outside the array bounds (I've generalized to sizeof(a))
Here is another way you can do this.
#include <stdio.h>
// define Start
#define ARRAY_SIZE 50
// define End
// Function Prototypes Start
void array_reader(char array[]);
void array_printer(char array[]);
// Function Prototypes End
int main(void) {
char user_input[ARRAY_SIZE];
printf("Please enter some characters (50 max)!\n");
array_reader(user_input);
printf("Here is what you said:\n");
array_printer(user_input);
return 0;
}
// Scans in characters into an array. Stops scanning if
// 50 characters have been scanned in or if it reads a
// new line.
void array_reader(char array[]) {
scanf("%c", &array[0]);
int i = 0;
while (
(array[i] != '\n') &&
(i < ARRAY_SIZE)
) {
i++;
scanf("%c", &array[i]);
}
array[i + 1] = '\0';
}
// Prints out an array of characters until it reaches
// the null terminator
void array_printer(char array[]) {
int i = 0;
while (array[i] != '\0') {
printf("%c", array[i]);
i++;
}
}
You may try with this code:
#include <stdio.h>
main()
{
char a[50];
int i;
printf("Give max 50 characters\n");
i=0;
do {
scanf("%c", &a[i]);
i=i+1;
} while(i<50 && a[i-1] != '\n');
a[i] = 0;
for(i=0; a[i] != 0; i++)
printf("%c", a[i]);
}
The function scanf("%c", pointer) will read one character at a time and place it at the pointer location. You are looking for '\0', which is a valid string terminator, but the newline character you get when you press ENTER and that you should be looking for is '\n'.
Also, it is a good idea to terminate the string you have read by adding a '\0' at the end (really a zero). Then use it to stop printing or you may print the "rest" of the contents of an uninitialized char array.
In this program I have taken a dimensional character array of size[3][4],
as long as I enter a 3 characters for each row it will work well.
For example: if I enter abc abd abd I get the same output but if i enter more letters in the first or second or 3rd row I get an error.
How should I check for null character in 2 dimensional?
# include <stdio.h>
#include <conio.h>
# include <ctype.h>
void main()
{
int i=0;
char name[3][4];
printf("\n enter the names \n");
for(i=0;i<3;i++)
{
scanf( "%s",name[i]);
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
getch();
}
As pointed out by #SouravGhosh, you can limit your scanf with "%3s", but the problem is still there if you don't flush stdin on each iteration.
You can do this:
printf("\n enter the names \n");
for(i = 0; i < 3; i++) {
int c;
scanf("%3s", name[i]);
while ((c = fgetc(stdin)) != '\n' && c != EOF); /* Flush stdin */
}
How should I chk for null character in 2 dimensional ... [something has eaten the rest part, I guess]
You don't need to, at least not in current context.
The problem is in your approach of allocating memory and putting input into it. Your code has
char name[3][4];
if you enter more that three chars, you'll be overwriting the boundary of allocated memory [considering the space of \0]. You've to limit your scanf() using
scanf("%3s",name[i]);
Note:
change void main() to int main(). add a return 0 at the end.
always check the return value of scanf() to ensure proper input.
EDIT:
As for the logical part, you need to eat up the remainings of the input words to start scanning from the beginning of the next word.
Check the below code [Under Linux, so removed conio.h and getch()]
# include <stdio.h>
# include <ctype.h>
int main()
{
int i=0; char name[3][4];
int c = 0;
printf("\n enter the names \n");
for(i=0;i < 3;i++)
{
scanf( "%3s",name[i]);
while(1) // loop to eat up the rest of unwanted input
{ // upto a ' ' or `\n` or `EOF`, whichever is earlier
c = getchar();
if (c == ' ' || c == '\n' || c == EOF) break;
}
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
return 0;
}
(Cringing after reading the answers to date.)
First, state the problem clearly. You want to read a line from stdin, and extract three short whitespace separated strings. The stored strings are NUL terminated and at most three characters (excluding the NUL).
#include <stdio.h>
void main(int, char**) {
char name[3][4];
printf("\n enter the names \n");
{
// Read tbe line of input text.
char line[80];
if (0 == fgets(line, sizeof(line), stdin)) {
printf("Nothing read!\n");
return 1;
}
int n_line = strlen(line);
if ('\n' != line[n_line - 1]) {
printf("Input too long!\n");
return 2;
}
// Parse out the three values.
int v = sscanf(line, "%3s %3s %3s", name[0], name[1], name[2]);
if (3 != v) {
printf("Too few values!\n");
return 3;
}
}
// We now have the three values, with errors checked.
printf("you entered these names\n%s\n%s\n%s\n",
name[0], name[1], name[2]
);
return 0;
}
you might consider something on the order of scanf( "%3s%*s",name[i]);
which should, if I recall correctly, take the first three characters (up to a whitespace) into name, and then ignore anything else up to the next white space. This will cover your long entries and it does not care what the white space is.
This is not a perfect answer as it will probably eat the middle entry of A B C if single or double character entries are mode. strtok, will separate a line into useful bits and you can then take substrings of the bits into your name[] fields.
Perhaps figuring out the entire requirement before writing code would be the first step in the process.
The problem I have is that I want to disable the user the possibility of putting character instead of number inside my program and optionally printing the message "it is disabled". It should ask for the value of the same variable. I tried to do this using this:
scanf(" %[0-9]d",&x);
and this:
else
result = scanf("%*s");
but it still does not work. What should I look for? I've searched internet, but I've only found solutions for C++ in which cin was used and unfortunately it does not work in C at all.
You can try something like this:
char c[SIZE];
int i;
// While the string is not a number
while(fgets(c, SIZE , stdin) && !isAllDigit(c));
where isAllDigit is:
int isAllDigit(char *c){
int i;
for(i = 0; c[i] != '\0' && c[i] != '\n'; i++) // Verify if each char is a digit
if(!isdigit(c[i])) // if it this char is not a digit
return 0; // return "false"
return 1; // This means that the string is a number
}
scanf isn't used much anymore as it is completely unsuitable for keyboard input. The basic scheme these days is to do fgets() + validate + sscanf() in a loop.
Ok, i'm a student in his first experiences with programmaing so be kind ;) this is the correct code to print "n" times a string on screen...
#include <stdio.h>
#include <string.h>
#define MAX 80+1+1 /* 80+\n+\0 */
int main(void)
{
char message[MAX];
int i, n;
/* input phase */
printf("Input message: ");
i = 0;
do {
scanf("%c", &message[i]);
} while (message[i++] != '\n');
message[i] = '\0';
printf("Number of repetitions: ");
scanf("%d", &n);
/* output phase */
for (i=0; i<n; i++) {
printf("%s", message);
}
return 0;
}
why in the do-while form he needs to check if message[i++] != '\n' and not just message[i] != '\n'??
The proper way to write that input loop is, in my opinion, something along the lines of:
fgets(message, sizeof message, stdin);
in other words, don't use a character-by-character loop, just use the standard library's function that reads a string terminated by newline and be done.
The do { ... } while(...) loop in your code reads characters one at a time and stores them in message. The index of the next character is one more that the index of the previous character, that's why we should increase index variable i after the current character is stored. The algorithm is:
Read the next character and store it in message[i].
If this character is '\n', exit.
Increase i and goto 1.
The expression message[i++] increments i after it was used as an index into message, so that next time we will look at the next character in the string. So, while (message[i++] != '\n') combines steps 2 and 3.
The same in for-loop:
int i;
for (i = 0; scanf("%c", &message[i]) && message[i] != '\n'; ++i);
But as #unwind pointed, it's better not to use char-by-char input.