Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'd like to ask you about my prog. The main purpose of this one is to fill the "result" array with data collect from "tab1" and "tab2" arrays. Could anybody check, why does results are so weird? Thank you.
#include <stdio.h>
#include <stdlib.h>
void laczenie(char tab1[],char tab2[])
{
int i;
char* result =(char*) malloc(100*sizeof(char));
for(i=0;i<30;i++)
{
if(tab1[i] != '\0') tab1[i]==result[i];
else if (tab2[i] !='\0')tab2[i]==result[i];
else printf(" ");
}
for(i=0;i<30;i++)printf("%c",result[i]);
free(result);
}
int main()
{
char x[10]={'n','a','p','i','s','1'};
char y[10]={'n','a','p','i','s','2'};
//char x[10] = {"napis1"};
//char y[10] = {"napis2"};
laczenie(x,y);
return 0;}
In addition to LihOs answer above this block looks wrong:
if(tab1[i] != '\0')
tab1[i]==result[i];
else if (tab2[i] !='\0')
tab2[i]==result[i];
else printf(" ");
Don't you mean to assign the value in tab1[i]or tab2[i] to result[i]like this?
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");
Also using magic numbers like in the loops: for(i=0;i<30;i++) is pretty bad practice, you should probably be using a constant for the size value (which you could then use in both the loops and in the array declarations. And why loop to 30 when the arrays is 10 elements only?
In your function you check for null-terminating character:
if(tab1[i] != '\0')
but where is null-terminating character here?
char x[10]={'n','a','p','i','s','1'};
Try:
char x[7]={'n','a','p','i','s','1','\0'};
Also note that tab1[i]==result[i]; compares tab[1] with result[i], if you want to assign the result[i] to tab1[i], use assignment operator =:
tab1[i]=result[i];
if(tab1[i] != '\0')
result[i] = tab1[i];
else if (tab2[i] !='\0')
result[i] = tab2[i];
else printf(" ");`
This is still wrong as by the time you assign tab2 to result i will be already at 6 so you will have to use two for loops i suppose for assign tab1 and tab 2
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This code doesn't do as intended - it should print out all of plaintext. I'm guessing there's something at work under the hood, but that logic escapes me. If you remove the else condition with underlying statement, it suddenly works.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
int main() {
string plaintext = get_string("plaintext: ");
int i;
for(i = 0; plaintext[i] != '\0'; i++)
if(isalpha(plaintext[i] != 0))
printf("%c", plaintext[i]);
//I intend to do stuff with alphabetic characters, but that code isn't relevant, so it's not included
else
printf("%c", 'a');
}
I'll be honest, this looks like magic to me. Why would adding an else condition affect whether the condition for the original if statement was met or not (if that's the case)?
Is it somehow because of using string in cs50.h?
for(i = 0; plaintext[i] != '\0'; i++)
if(isalpha(plaintext[i] != 0))
printf("%c", plaintext[i]);
else
printf("%c", plaintext[i]);
is the same as :
for(i = 0; plaintext[i] != '\0'; i++)
printf("%c", plaintext[i]);
because any logical operation may have two results: true and false. If in both cases you do exactly the same, why do you check the condition?
another problem :
if(isalpha(plaintext[i] != 0))
it should be
if(isalpha(plaintext[i]) != 0)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have to write a program that acts like a shell. I wrote the function that gets the input from the user. I also wrote the function that splits it into arguments. The first time I type something, it works well, but the second time, it prints different characters after the ones that I gave it. I don't have to print it in the program. I was just doing it to see if it works correctly. I read a bunch of stuff online, but I can't figure out my error. I suppose it is in makeArgs(), but I can't pinpoint it.
Also, when I give it an input, the readline function adds a \n at the end of the string. I suppose it is from the fact that I press the enter key. I managed to solve the issue, by manually replacing it, but I would like to know if it is normal.
Any help really be appreciated.
Thank You
Screenshot of Xterm after 2 inputs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getText();
int makeArgs();
char *textEntre;
size_t nbCharacters;
char **arguments;
int main (void)
{
while (1){
getText();
int nbArguments = makeArgs();
for(int i =0; i<5; i++){
printf("%s \n",arguments[i]);
}
for(int i=0; i<nbArguments; i++){//free the char ptrs at the end
free(arguments[i]);
}
}
free(textEntre);
free(arguments);
return 0;
}
int getText(){
size_t buffersize = 0;
nbCharacters = getline(&textEntre, &buffersize, stdin);
textEntre[nbCharacters-1] =' '; // when I press enter it regiter the enter as \n so I replace it with a space
return 0;
}
int makeArgs(){
arguments = (char **)malloc(sizeof(char*)*20);
int i;
int j = 0;
int k = 0;
int nbElem = 20; //the number of ptrs that can be in arguments
for(i = 0; i<nbCharacters; i++){
if(i == 20){ //increases the memory allocated if there are more than 20 arguments
nbElem = nbElem *2;
arguments = (char **)realloc(arguments, sizeof(char*)*nbElem);
}
if(textEntre[i] == '"'){ //checks for ""
i++;
while(textEntre[i] != '"'){
i++;
}
}
if(textEntre[i] == ' ' && textEntre[i-1] == ' '){ // eliminates useless spaces
j++;
}
else if(textEntre[i] == ' '){ //save a single argument
char * chptr;
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
strncpy(chptr, &textEntre[j], i-j);
arguments[k] = chptr;
k++;
j = i +1;
}
}
return k;
}
chptr = (char *)malloc(i-j+1); //giving +1 for the \0 at the end
You properly allocated memory for that terminating \0, but where do you actually add that "\0 at the end"?
strncpy(chptr, &textEntre[j], i-j);
strncpy does not necessarily zero-terminate the destination buffer. You have to do it yourself.
In fact, in this specific application strncpy is a rather inappropriate function: it does not give you anything over ordinary memcpy and might be less efficient. You could just do
memcpy(chptr, &textEntre[j], i - j);
with potentially better efficiency. And, again, don't forget to zero-terminate the destination buffer.
Or you can use sprintf for the same purpose as follows
sprintf(chptr, "%.*s", i - j, &textEntre[j]);
which will produce a properly zero-terminated string in the destination. (Albeit you won't see sprintf used that way very often.)
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 5 years ago.
Improve this question
How would one go about adding integers together like this.
Say you start with 1, then you add 2. So you have 12, next add 3, so you have 123. And so on.
I would just concatenate but I'm not allowed to use strings in this program.
Using some unusual math (based on the mechanisms of the decimal system) to make the desired variation of adding:
Code:
#include <stdio.h>
int main(void)
{
int i;
int number=0;
for (i=1; i<5; ++i)
{
number=number*10 + i;
printf("%d\n", number);
}
return 0;
}
Output:
1
12
123
1234
Like this?
#include <stdio.h>
int main() {
int a = 4, b = 5, c = 6, d = 7;
printf("a+b=%d\n",a*10+b);
printf("a+b+c=%d\n",(a*10+b)*10+c);
printf("a+b+c+d=%d\n",((a*10+b)*10+c)*10+d);
return 0;
}
This can be typical case to use realloc
char *mystr = NULL;
char *temp;
char c, ch;
short count = 0;
do {
printf("Enter character : ");
scanf(" %c", &c); // Better use sscanf or fgets, scanf is problematic
temp = (char*)realloc(mystr, (++count) * sizeof *mystr);
if (NULL != temp) {
mystr = temp;
mystr[count - 1] = c;
}
printf("Do you wish to continue: ");
scanf(" %c", &ch);
} while ('y' == ch);
// Since and since you don't have a null terminated string, do
for (int i = 0; i < count; i++)
printf("%c", mystr[i]);
printf("\n");
free(mystr); // Freeing the memory
getch();
Note : And you don't have strings in this program ;)
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 5 years ago.
Improve this question
I need to write a program which converts a number from one base to another.
i need to get a user input in the form of: <original base><new base><number in original base>
I’m not allowed to use scanf and also im not allowed to assume the size of the line.
I have already tried using fgets() but I don’t know how to use it without limiting the size. I would love to get some ideas of what to do. Thanks.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int BaseChanger()
{
char input[12];
printf("enter the original base, new base ,number");
fgets(input, 12, stdin);
}
You can use this snippet as a form of getline
int max= 100;
char* array;
array = malloc(max*sizeof(char));
if(array == NULL)
exit(1);
int c,i=0;
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
array[ i++ ] = c ;
if( i == max)
{
char * narray = realloc(array, max *= 2);
if( narray == NULL ){
free(array);
exit(1);
}
array = narray;
}
...
}
Once you do this, extract the numbers and then do the rest of the logic.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int i=0,j=0;
char string[100], string2[100];
scanf("%s",&string);
while (string[i]!='\0'){
if(string[i]=='a' || string[i]=='e' || string[i]=='i' || string[i]=='o' || string[i]=='u' || string[i]=='A' || string[i]=='E' || string[i]=='I' || string[i]=='O' || string[i]=='U'){
string[i]=string2[j];
}
string[i] = tolower(string[i]);
string[i] = string2[j];
string2[j-1]='.';
}
printf("%s", string2);
return 0;
The question is entering a word and then removing all vowels, adding '.' after every constant and making all upper case letters lower case.
Since string is an array, you don't use & when passing it to scanf(), this gives you a double pointer and is an error. Any time you find yourself with a 10 clause if statement, you're just asking for problems (e.g. easy to get tripped up by typos.) You can simplify this test with index() and a string containing all the vowels. It wouldn't hurt to comment as you write your code to indicate which of the requirements each section implements. The i variable needs to be incremented every time through the loop, the j variable needs to be incremented every time a new character is added to string2. After the scanf(), you shouldn't be assigning into string, treat it as readonly, only assign into string2. And j-1 shouldn't happen. Finally, since string2 isn't intialized, there may be garbage in it and you haven't null terminated it. Putting it all together:
#include <ctype.h>
#include <stdio.h>
#include <strings.h>
#define VOWELS "AEIOUaeiou"
int main()
{
char string[100], new_string[100] = { 0 };
// enter a word
scanf("%s", string);
for (int i = 0, j = 0; string[i] != '\0'; i++)
{
// remove all vowels
if (index(VOWELS, string[i]) == NULL)
{
// make all upper case letters lower case
new_string[j++] = tolower(string[i]);
if (isalpha(string[i]))
{
new_string[j++] = '.'; // add '.' after every consonant
}
}
}
printf("%s\n", new_string);
return 0;
}
I'm assuming "after every constant" was meant to read "after every consonant", otherwise please clarify what you mean by constant.