How to store array in address C - c

basically we are provided with the main function:
#include <stdio.h>
#include <string.h>
#include <strings.h>
#define STORAGE 255
{
int c;
char s[STORAGE];
for(;;) {
(void) printf("n=%d, s=[%s]\n", c = getword(s), s);
if (c == -1)break;
}}
we are not to change that
and we have to create the function getword() which should contain a loop that reads a characters,
store it in a array in the address provided one by one and it should stop for whitespace (tab, space, eof)
basically i have this:
int getword(char *w)
{
char str[255];
int i = 0;
int charCount = 0;
printf("enter your sentence:\n");
gets(str);
/*this was provided by the professor, but i'm not sure how to use it
while (( iochar - getchar()) !=EOF);
*/
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
return 0;}
right now the output of the program is:
enter your sentence:
hey stockoverflow
your string: 'hey stockoverflow' contains 16 of letters
n=0, s=[]
so i'm saving the string and counting it, but i'm not storing it where i should be.
it should display n=16, s=[hey stockoverflow]
actually it should display n=3, s=[hey]
any help would be appreciated

This may be what you are looking for:
for(i = 0; str[i] != '\0'; i++) //loop that checks tab and spaces
{
if(str[i] != ' ' && str[i] != '\t')
{
charCount++;
}
else
{
str[i] = '\0'; // Terminate str
break; // Break out of the for-loop
}
}
printf("your string: '%s' contains %d of letters\n", str, charCount);
strcpy(w, str); // Add this line to copy str into w (which is s from main)
return strlen(w); // Return the length of the result string

Related

How do I modify this program to count the number of characters that aren't spaces?

For my assignment I need to modify the following program. I can not use strings.h.
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces);
return 0;
}
I tried using
if (c != EOF)
countSpaces = countSpaces + 1;
}
while (c != '\n');
printf("Sentence contains %d Spaces.\n", countSpaces - 1);
but that seems like a hacky and unelegant way to do this.
Can anyone help and/or explain to me how to do this better?
Thanks in advance
The code I posted counts the spaces in a sentence, I want to modify it to count all the characters in the input sentence. – fbN 21 secs ago
Have another counter outside the if condition.
#include <stdio.h>
int main(void)
{
int c;
int countSpaces = 0;
int countChars = 0;
puts("Type sentence:");
do {
c = getchar();
countChars += 1;
if (c == ' ') {
countSpaces += 1;
}
} while (c != '\n');
printf("Sentence contains %d spaces and %d characters.\n", countSpaces, countChars);
return 0;
}
Two notes. foo += 1 is shorthand for foo = foo + 1 without the precendence complexities of foo++.
Blockless if or while is playing with fire. Eventually you'll accidentally write this.
if( condition )
do something
whoops this is not in the condition but it sure looks like it is!
Always use the block form.
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 12 characters.
Note this says 12 because it's including the newline. That's because it's checking what c is after it's already been counted. You can fix this by checking c as its read. This is a fairly normal "read and check" C loop idiom.
// Note, the parenthesis around `c = getchar()` are important.
while( (c = getchar()) != '\n' ) {
countChars++;
if (c == ' ') {
countSpaces++;
}
}
$ ./test
Type sentence:
foo bar baz
Sentence contains 2 spaces and 11 characters.
I always prefer to use fgets() when reading a line from the console (stdin):
#include <stdio.h>
int main(void)
{
int i;
int length = 0;
char buffer[1024];
printf( "Enter some text> " );
fgets( buffer, sizeof(buffer), stdin );
// If the user inputs > 1024 letters, buffer will not be \n terminated
for ( i=0; buffer[i] != '\n' && buffer[i] != '\0'; i++ )
{
length += 1;
}
printf( "length: %d\n", length );
return 0;
}
I make this code that count length of the string given It's like strlen function.
and I used just scanf and it works perfectly even with spaces.
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int i = 0, count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
while (str[i++] != '\0')
count++; //length of the string
printf("%d",count);
return 0;
}
and if you want just to count the characters in the string given use this code below:
#include <stdio.h>
int main()
{
char *str = calloc(sizeof(char),50);
int count = 0;
printf("Type sentence:\n");
scanf("%[^\n]",str);
for (int i = 0; str[i] != '\0'; i++)
if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
count++;
printf("Sentence contains %d characters.\n",count);
return 0;
}
the output :
Type sentence:
hello world
Sentence contains 10 characters.
you can just calculate the result like this
int main(void)
{
int c, countSpaces = 0;
printf("Type sentence:\n");
do
{
c = getchar();
if (c == ' ')
countSpaces++;
}
while (c != '\n');
int countChar = c - countSpaces - 1 ; // -1 new line
printf("Sentence contains %d Spaces.\n", countSpaces);
printf("Sentence contains %d chars.\n", countChar);
return 0;
}

How to count the number of words, characters and lines with pure C

I want to count the number of words, characters, new lines, no matter how my sentence looks like. (For example, even if I typed a sentence like this:
y yafa \n \n youasf\n sd
the program should still be able to count the number of words, lines, characters correctly). I don't know how to implement such program with pure C, can anyone help me on that?
Here is my current code, and it can only be correct under certain conditions...
int main() {
int cCount = 0, wCount = 0, lCount = 0;
printf("Please enter the sentence you want\n");
char str[20];
int j7 = 0;
while (int(str[j7]) != 4) {
str[j7] = getchar();
if (str[0] == ' ') {
printf("Sentence starts from a word not blank\n");
break;
}
if (int(str[j7]) == 4)
break;
j7++;
}
int count = 0;
while (count < 20) {
if (str[count] != ' ' && str[count] != '\n') {
cCount++;
} else
if (str[count] == ' ') {
wCount++;
} else
if (str[count] == '\n') {
lCount++;
}
count++;
}
printf("Characters: %d\nWords: %d\nLines: %d\n\n",
cCount, wCount++, lCount + 1);
int x = 0;
std::cin >> x;
}
You are not writing in Pure C, but rather in C++.
To achieve your goal, you must summarize the problem into a sequence of logical steps:
for each character read:
if the previous one is a line separator, you have a new line ;
if the previous one is a word separator and the current isn't, you have a new word ;
if all cases, you have a new character, save it as the previous character for the next iteration.
Use '\n' as the initial value for the last character, so the first character read if any starts a new line and possibly a new word if it is not whitespace.
Here is a simple implementation:
#include <ctype.h>
#include <stdio.h>
int main(void) {
long chars = 0, words = 0, lines = 0;
printf("Enter the text:\n");
for (int c, last = '\n'; (c = getchar()) != EOF; last = c) {
chars++;
if (last == '\n')
lines++;
if (isspace(last) && !isspace(c))
words++;
}
printf("Characters: %ld\n"
"Words: %ld\n"
"Lines: %ld\n\n", chars, words, lines);
return 0;
}
If you are required to use a while loop, the for loop can be converted this way:
#include <ctype.h>
#include <stdio.h>
int main(void) {
long chars = 0, words = 0, lines = 0;
int c, last = '\n';
printf("Enter the text:\n");
while ((c = getchar()) != EOF) {
chars++;
if (last == '\n')
lines++;
if (isspace(last) && !isspace(c))
words++;
last = c;
}
printf("Characters: %ld\n"
"Words: %ld\n"
"Lines: %ld\n\n", chars, words, lines);
return 0;
}

I want my code to print the frequency of characters in the order of appearance of string

My code is printing the frequency of characters in random order. What can be done so that it prints the frequency of characters in order in which the word is given. My current code is as follows
#include <stdio.h>
#include <conio.h>
void main() {
char string1[50];
int i = 0, counter[26] = { 0 };
printf("\nEnter a string\n");
//Inputs a string
gets(string1);
while (string1[i] != '\0') {
//checks and includes all the characters
if (string1[i] >= 'a' && string1[i] <= 'z') {
//counts the frequency of characters
counter[string1[i] - 'a']++;
i++;
}
}
//printing frequency of each character
for (i = 0; i < 26; i++) {
if (counter[i] != 0)
printf("%c occurs %d times.\n", i + 'a', counter[i]);
}
getch();
}
sample output:
There are several issues in your code:
you use gets: this function is unsafe, it was removed from the current version of the C Standard.
you increment i only for if string1[i] is a lowercase letter: you will run an infinite loop if you type any other character.
the proper prototype for main is either int main(void) or int main(int arc, char *argv[]).
you only count lower case letters. H is upper case, thus not counted.
Here is an improved version:
#include <stdio.h>
#include <ctype.h>
int main(void) {
char string1[128];
int i = 0, counter[256] = { 0 };
printf("\nEnter a string\n");
//Inputs a string
if (fgets(string1, sizeof string1, stdin) == NULL) {
// empty file: got an empty line
*string1 = '\0';
}
for (i = 0; string1[i] != '\0'; i++) {
if (isalpha((unsigned char)string1[i])) {
//counts the frequency of letters
counter[string1[i]]++;
}
}
//printing frequency of each counted character
//characters are printed in the order of appearance
for (i = 0; string1[i] != '\0'; i++) {
if (counter[string1[i]] != 0) {
printf("%c occurs %d times.\n",
string1[i], counter[string1[i]]);
counter[string1[i]] = 0; // print each letter once.
}
}
getch();
return 0;
}
You can get the characters printed in order of their appearance by using the string a second time to generate the output.
In your section where you are "printing the frequency of each character", use the code to process the input string. This time, if the frequency value is not zero, print it and then reset the frequency value to zero. If the frequency value is zero, you must have already printed it so do nothing.
//printing frequency of each counted character (in input order)
for (i = 0; string1[i] != '\0'; i++) {
char ch = string[i];
if (counter[ch - 'a'] != 0) {
printf("%c occurs %d times.\n", ch, counter[ch - 'a']);
counter[ch - 'a'] = 0;
}
}

why my code is printing output for input text containing more than 10 characters?

#include<stdio.h>
main() {
char ch, a[10];
int i = 0;
printf("enter text,press <return> to end!\n");
while (ch != '\n') {
ch = getchar();
a[i] = ch;
i++;
}
i = i - 1;
a[i] = '\0';
printf("%s", a);
}
here i declared an array 'a' of maximum size 10.I used a while loop to read characters and place them in array 'a' and finally the code prints the text i have entered
I've done a little more checking in this version.
#include <stdio.h>
#define STRLEN 10
int main(void) { // correct signature
char ch, a[STRLEN+1]; // room for terminator
int i = 0;
printf("Enter text, press <return> to end!\n");
while(i < STRLEN && (ch = getchar()) != EOF && ch != '\n') // more checks
a[i++]=ch; // excludes newline
a[i]='\0'; // terminate string
printf("%s\n",a); // added newline
return 0;
}
This is really unsafe as you have a statically declared array of 10 chars. If the user enters a 11th char you will encounter buffer overflow. You should check i in your while too:
while(ch!='\n' && i < 9) {
ch=getchar();
a[i]=ch;
i++;
}
a[i]='\0';
printf("%s",a);

two dimensional array in c, reversing and storing a sentence

Hey I'm really new to programming and having trouble with arrays. Can someone help me with this project. "c programming a modern approach: modify a program that reverses the words of a sentence so that it stores the words in a two dimensional char array as it reads the sentence, with each row of the array storing a single word. assume that the sentence contains no more than 30 words and no word is more than 20 characters long. Be sure to store a null character at the end of each word so that it can be treated as a string"
(also i don't get what its saying about the null character).
here's my try but it's not working. i think i'm close though.
#include <stdio.h>
#define MAX_SENTENCE_LEN 80
#define SENTENCE_MAX 30
#define WORD_MAX 20
int main(void)
{
char ch, sentence[MAX_SENTENCE_LEN] = {' '}, terminator = '.';
int n, i, j, start, finish;
printf("Enter a sentence: ");
for (n = 1; n < MAX_SENTENCE_LEN; n++) {
ch = getchar();
if (ch == '.' || ch == '?' || ch == '!') {
terminator = ch;
break;
}
sentence[n] = ch;
}
printf("Reversal of sentence:");
finish = n;
for (start = finish - 1; start >= 0; start--) {
if (sentence[start] == ' ') {
for (i = start; i < finish; i++)
putchar(sentence[i]);
finish = start;
}
{
int sentence[SENTENCE_MAX][WORD_MAX];
int word[30][20];
for (i=0; i< SENTENCE_MAX;i++){
for (j=0; j<WORD_MAX; j++)
sentence[i][j]=-1;
}
}
}
printf("%c\n", terminator);
return 0;}
i wrote a new code which i think is closer to what i want but it still won't run. do i have a faulty compiler or what?
anyway here's the new code
#include<stdio.h>
#define N 100
int main (void)
{
char sentence[N][N], ch, termChar;
int i = 0, l = 0, count = 0;
int j = 0, k, start, finish, word;
printf("enter a sentence: ");
while (ch = getchar())
{
sentence[i][l++]= ch;
if (ch == ' ')
{
sentence[i][l] = '\0';
i++;
l = 0;
count++;
}
if (ch == '.' || ch == '!' || ch == '?')
{
sentence[i][l-1]= ' ';
sentence[i][l]= '\0';
termChar = ch;
count ++;
break;
}
}
for(i=count ; i>=0; i--)
printf("%s ", sentence[i]);
printf("%c\n", termChar);
return 0;
}
Your code worked perfectly in my environment (Windows, C99 compiler, 32bit build). I entered a short sentence, and it reversed it:
Regarding: i don't get what its saying about the null character
a C string is defined by a null character: \0, at the end of a char array. example char string[]="word" looks like: |w|o|r|d|\0| in memory.
Without the \0, it would simply be a char array, but not a string, and would therefore not be useable in any of the string functions such as strcpy(), strlen(), etc.
By the way, sentence creation and initialization:
char sentence[MAX_SENTENCE_LEN] = {' '};
Does not guarantee contents for the entire length of the char array.
This may be the reason your environment is not running your code, while my environment does.
Depending on compiler, OS, and other random factors, sentence could be filled with anything. So, if your code is not running on your machine, it is likely that you just need to initialize sentence to \0. Replace that line with these:
char sentence[MAX_SENTENCE_LEN]; //create
memset(sentence, 0 ,MAX_SENTENCE_LEN); //zero all memory
sentence[0]=' '; //set first char to a space (' '). (not sure why)
Also by chance, if the user input results in string length == MAX_SENTENCE_LEN, then your program will crash as there is only enough room in sentence for MAX_SENTENCE_LEN-1 + \0.
#include <stdio.h>
#define MAX_SENTENCE_LEN 80
#define SENTENCE_MAX 30
#define WORD_MAX 20
int main(void){
char ch, sentence[MAX_SENTENCE_LEN] = {' '}, terminator = '.';
int n, i, j, start, finish;
char word[SENTENCE_MAX][WORD_MAX+1];
int wc=0, wcc=0;
printf("Enter a sentence: ");
for (n = 1; n < MAX_SENTENCE_LEN; n++) {
ch = getchar();
if (ch == '.' || ch == '?' || ch == '!') {
terminator = ch;
break;
} else if(ch != ' '){
word[wc][wcc++] = ch;
} else if(ch == ' '){//this is assumed to be one space between words.
word[wc++][wcc] = '\0';//null character
wcc = 0;
}
sentence[n] = ch;
}
word[wc++][wcc] = '\0';
printf("Reversal of sentence:");
finish = n;
for (start = finish - 1; start >= 0; start--) {
if (sentence[start] == ' ') {
for (i = start; i < finish; i++)
putchar(sentence[i]);
finish = start;
}
}
printf("%c\n", terminator);
for(i=wc-1;i>=0;--i){
printf("%s", word[i]);
if(i>0)
putchar(' ');
}
printf("%c\n", terminator);
return 0;
}

Resources