Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
This is the text of my example:
Loading number N then N words from standard input. The word is not longer than 100 characters. Dynamically allocate array of loaded words as a series of pointers to character strings (dynamic array needs to have a type char **). Provide a set of words printed in a single line with spaces between the words.
Can someone tell me how to set the character limits?
Should I do this:
scanf("%100s", str[i])
or something else?
BTW, how can I allocate the memory for a type like this (char **,int **,etc)?
This is my code that I've done, so what have I done wrong?
int main()
{
int i,n;
printf("How much words? "), scanf("%d", &n);
char *str= (char *)malloc(n*sizeof(char *));
for(i = 0; i < n; i++)
{
str[i] = malloc(100 * sizeof(char *));
printf("%d. word: ", i + 1),scanf("%s", str[i]);
}
for (i = 0; i < n; i++)
{
printf("%s ", str[i]);
}
getch();
Wrong type for array of pointers
// char *str
char **str
Code clean-up with comments.
// add void
int main(void) {
int i,n;
// Easier to understand if on 2 lines-of code
printf("How much words? ");
// test scanf() results
if (scanf("%d", &n) != 1) return -1;
// Consider different style to allocate memory, as well as type change
// char *str= (char *)malloc(n*sizeof(char *));
char **str= malloc(sizeof *str * n);
// check allocation
assert(str == NULL);
for(i = 0; i < n; i++) {
str[i] = malloc(sizeof *str[i] * 100);
// check allocation
assert(str[i] == NULL);
printf("%d. word: ", i + 1);
fflush(stdout);
// limit input width to 99
// test scanf() results
if (scanf("%99s", str[i]) != 1) return -1;
}
for (i = 0; i < n; i++) {
// Add () to clearly show beginning/end of string
printf("(%s) ", str[i]);
}
getch();
}
Related
This question already has answers here:
Function to reverse string in C
(4 answers)
Closed 6 years ago.
Beginner programmer here. I'm trying to take an input from user, reverse it and show the result. For some reason, it's printing blanks instead of the reversed string. I know that array[i] has the right information because if I use this loop on line for (int i=0; i<count; i++), it's printing the right characters. It's just not printing in reverse. What am I not getting here?
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
printf("Please enter a word: ");
char *word = get_string();
int count = strlen(word);
char array[count];
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
for (int i=count-1; i==0; i--)
{
printf("%c ", array[i]);
}
printf("\n");
}
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
You go over the string and copy it, you do not reverse it.
There is also a subtle bug in-waiting in your declaration of array, since you do not leave space for the '\0' character terminator. Passing your buffer to printf as a C-string, as opposed to character by character will have undefined behavior.
So to fix those two particular errors:
char array[count + 1];
array[count] = '\0';
for (int i = 0; i< count; i++)
{
array[i] = word[count - i];
}
As a side note, it may not mean much to use a VLA for this small exercise, but for larger inputs it could very well overflow the call stack. Beware.
// the header where strlen is
#include <string.h>
/**
* \brief reverse the string pointed by str
**/
void reverseString(char* str) {
int len = strlen(str);
// the pointer for the left and right character
char* pl = str;
char* pr = str+len-1;
// iterate to the middle of the string from left and right (len>>1 == len/2)
for(int i = len>>1; i; --i, ++pl, --pr) {
// swap the left and right character
char l = *pl;
*pl = *pr;
*pr = l;
};
};
And just call the function:
int main(void) {
printf("Please enter a word: ");
char *word = get_string();
// Just call the function. Note: the memory is changed, if you want to have the original and the reversed just use a buffer and copy it with srcpy before the call
reverseString(word)
printf("%s\n", word);
};
And just change
char array[count];
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
to
// add an other byte for the null-terminating character!!!
char array[count+1];
strcpy(array, word);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to make a program that can find characters in long string...
.
.
int i = 0;
char buf[100];
char ch[10];
char *res;
int len = 0;
int j = 0;
printf("Enter characters: ");
while(1){
j = getchar();
if(j == '\n') break;
ch[i++] = j;
}
ch[i] = '\0';
while(len < 1){
printf("Enter a sentence: ");
res = fgets(buf, 200, stdin);
len = strlen(buf);
}
Here's sample execute screen.
Enter characters: mkn
Enter a sentence: My son is in elementary school.
Finding..
-
My
son
in
elementary
I want to make this program with strtok() and strchr()... but I am confused with pointers....
Though they may not be the best choices for this purpose, you can achieve what you want with strtok() and strchr(). Below is how I picture building on what you already have to get a working solution:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define CHARACTERS_MAXIMUM 32
#define BUFFER_MAXIMUM 1024
int main() {
char characters[CHARACTERS_MAXIMUM];
int characters_length = 0, character;
printf("Enter characters: ");
while (characters_length < CHARACTERS_MAXIMUM - 1) {
character = getchar();
if (character == '\n') {
break;
}
characters[characters_length++] = tolower(character);
characters[characters_length++] = toupper(character);
}
characters[characters_length] = '\0';
char buffer[BUFFER_MAXIMUM], *result = NULL;
int buffer_length = 0;
while (buffer_length < 1 || result == NULL) {
printf("Enter a sentence: ");
if ((result = fgets(buffer, BUFFER_MAXIMUM, stdin)) != NULL) {
buffer_length = strlen(buffer);
}
}
char *token = strtok(buffer, " ");
while (token != NULL) {
for (int i = 0; i < characters_length; i++) {
if (strchr(token, characters[i]) != NULL) {
printf("%s ", token);
break;
}
}
token = strtok(NULL, " ");
}
printf("\n");
return 0;
}
Note that this is not a finished program, there's more/better error checking you should do as well as other tweaks to finish it off properly.
USAGE EXAMPLE
> ./a.out
Enter characters: mkn
Enter a sentence: My son is in elementary school.
My son in elementary
>
Although the above is an appropriate use of strtok(), be wary of it. It is an artifact of an earlier age and should be avoided in favor of safer, modern library functions like strsep() or strtok_r().
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm receiving an uknown error found in the stdio.h library.
Please can someone check it at tell me what is wrong with the code (But I thing it should work fine).
P.S. I'm new here so please don't blame me if this is a bad question.
Code:
#include <stdio.h>
#include <stdlib.h>
// Conversion from a number to a string
char *i2s(int broj);
int main()
{
char string1;
int br, n;
do
{
printf("How much numbers?\n -"), scanf("%d", &n);
} while (n < 1);
for (int i = 0; i < n; i++)
{
printf("\nbr = "), scanf("%d", &br);
string1 = *i2s(br);
printf(" %s", string1);
}
free(string1);
getch();
return 0;
}
char *i2s(int broj)
{
char *pom;
int z=0,br=0,p;
if (broj < 0)
{
z = 1;
broj = -broj;
}
p = broj;
do
{
br++;
p /= 10;
} while (p);
pom = (char *)calloc(br + 1 + z, sizeof(char));
if (z)
pom[0] = '-';
do
{
pom[--br + z] = '0' + broj % 10;
} while (broj /= 10);
return pom;
}
char string1;
free(string1);
string 1 is not a pointer.
Also with the following section you overwrite string1 everytime you run through the loop. that way you have no pointer to free() the memory that you allocate inside your function unless you do it inside the loop.
for (int i = 0; i < n; i++)
{
printf("\nbr = "), scanf("%d", &br);
string1 = *i2s(br);
printf(" %s", string1);
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I count sum of characters in string excluding blank spaces?! I wrote a code but it counts blank spaces too. Any suggestions? here is what I have:
void main()
{
char str[100];
int len, space;
printf( "Enter string:\n ");
printf("\n");
gets(str);
len = strlen(str);
printf("\n");
printf("\n No.of characters in string is %d " , len );
getch();
}
For simple spaces try this
len = strlen(str);
int nchar = 0
for(int i = 0; i != len; i++) {
if(str[i] != ' ') {
nchar++;
}
}
printf("nchar = %d\n", nchar);
For all whitespace ( space, tab, newline ) try this:
#include <ctype.h> // this line must be in the top of the file
len = strlen(str);
int nchar = 0;
for(int i = 0; i != len; i++) {
if(!isspace(str[i])) {
nchar++;
}
}
printf("nchar = %d\n", nchar);
Other ways you might see in code are:
int nchar = 0;
for(char *p = str; *p; nchar += (*p++ != ' '));
and
int nchar = 0;
for(char *p = str; *p; nchar += isspace(*p++) == 0);
But those are less obvious.
You need to iterate over string and check all characters, counting only non-space chars. Something like:
int i;
int len = strlen(str);
int count = 0;
for (i = 0; i < len; i++) {
char c = str[i];
if ( /* check that char is not space */ )
count++;
}
Alternatively, you can count all space characters and then calculate len - nspaces.
This question already has an answer here:
Dynamic Memory Allocation
(1 answer)
Closed 8 years ago.
I'm having trouble dynamically allocating memory for an array.
The program is simply supposed to exchange the swap the first row with the second, and the third with the forth. I am getting strange results like:
Enter string: hello
Enter string: how are you
Enter string: i'm good thanks
Enter string: bye
Enter string: bai
Enter string: xx
=========================
how are you
!i'm good thanks
hello
!how are you
bye
!bai
i'm good thanks
!bye
bai
!xx
int count = 0;
char *lines[MAX_LINES];
char *tmp[50];
printf("Enter string: ");
fgets(tmp, 50, stdin);
lines[count] = (char *) malloc((strlen(tmp)+1) * sizeof(char));
strcpy(lines[count], tmp);
while(strcmp("xx\n", lines[count])){
count++;
printf("Enter string: ");
fgets(tmp, 50, stdin);
lines[count] = (char *) malloc((strlen(tmp)+1)* sizeof(char));
strcpy(lines[count], tmp);
}
void exchange(char * records[])
{
char * temp;
temp = records[0];
records[0] = records[1];
records[1] = temp;
temp = records[2];
records[2] = records[3];
records[3] = temp;
}
void printArray(char * inputs[], int row, int col)
{
int i, j;
for(i = 0; i < row; i++){
for(j = 0; j < col; j++){
printf("%c", inputs[i][j]);
}
}
}
This is not good:
char *tmp[50];
You intended to do this:
char tmp[50];
Strangely enough, it'll kinda work, but your compiler should have been throwing up warnings everywhere.
I think your main problem is your printArray function, which doesn't check for the NULL terminator in a string. So it's gonna run right off the end of most of them.
Instead of printing character-by-character, do this:
void printArray(char * inputs[], int length)
{
int i;
for(i = 0; i < length; i++){
printf("%s", inputs[i]);
}
}
Here's a tip on using malloc. Don't cast the result, and if you're reserving space for char values, don't use sizeof(char) -- it's always 1.
lines[count] = malloc( strlen(tmp) + 1 );