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 new to C programming and I know there have been other explanations on how to split a string into words but none of them seem similar to my program. I'm having difficulty finding the errors in my program:
#include <stdio.h>
#include <stdlib.h>
int tokenise(char str[], int start, char result[]) {
if (str[start] == "/o") {
return -1;
} else {
result = str[start];
}
}
int main() {
const int MAX_STRING = 256;
char buffer[MAX_STRING];
fgets(buffer, MAX_STRING, stdin);
char result[256];
int start;
start = tokenise(buffer, 0, result);
while ( start != -1 ) {
printf("%s\n", result);
start = tokenise(buffer, start, result);
}
}
In your function tokenise -
if(str[start] == "/o"){
What is "/o" you compare with? It should be '\0'.
if(str[start] == '\0'){
And in else your function does not return anything , therefore , in that case UB.
You function doesn't have any loop or use recursion to iterate over array ,therefore , your logic doesn't seem to achieve anything close .
You have many problems with your code:
else {
result = str[start];
}
No return value. That is undefined behaviour.
str[start] == '\o'
Thats incorrect as you want to compare to the EOS null termination character
Do this instead:
str[start] == '\0'
Lastly, if you want your tokenise function to write into result, you need to pass a pointer to result, not the value of result.
ps: semantic errors aside, your function does nothing resembling what you want. Look into loops and their implementation.
Related
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 5 years ago.
Improve this question
There is a following exercise:
I have a file.txt containing a lot of unknown numbers, separated by one or more spaces or by a new line.(file.txt in one folder with my program).
I must find total amount of numbers and maximum value. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *in;
in=fopen("file.txt","r");
int arr[100],i=0,j,max;
while(fscanf(in,"%d",&arr[i] != EOF)) {
i++;
}
arr[0]=max;
for(j=1;j<i;j++) {
if(max < arr[j]) {
max = arr[j];
}
}
printf("Tot.number: %d\nMax: %d",i,max);
}
But, codeblock cannot execute the program.
fscanf(in,"%d",&arr[i] != EOF)
will be
fscanf(in,"%d",&arr[i]) != EOF
But there are other problems also
Not checking the return value of fopen.
if(in != NULL ){
/* File opened correctly */
}
No guard while accessing the array. if i>=100 there will be array index out of bound error leading to undefined behavior.
You forgot to declare initialize max.
You meant to initialize max to arr[0]. So correct will be max = arr[0]. There is no use assigning value of arr[0] in case you want to find the maximum.
Also you have to keep in mind that if fscanf doesn't return EOF then you can't be relieved that it worked unless you check that 2 value is being parsed correctly. The output of fscanf should be equal to 1 since one value is being read.
int r = fscanf("%d",&arr[i]);
if( r == 1 ){
/* SUCCESS */
}
else if( errno ) {
/* Error occured */
}
else if( r == EOF ){
/* Either EOF reached or some I/O error. */
}
Also among other things (not an error but a good practice)
Not closing the file.
fclose(in);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am a beginner C-programmer. Recently I've been trying to practise using string functions in C.
As such, I wrote the following program:
MessageDetector.c
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[100] = "Alex:HeyGoodMorning!:1911hrs:0:1012:2017:::";
char *p = strtok(a,":");
char n[20];
int i = 1;
while(p != NULL) {
strcpy(n,p);
p = strtok(NULL,":"); //limit to characters before semi-colon
i++;
if (i = 2) { //after 2 occurrences of the semi-colon. print a string
printf("%s\n",n);
break;
}
}
return 0;
}
The output of my program is as follows:
Alex
However, I would like the program to output
HeyGoodMorning!
What are the changes I should make to the above program? Your help is greatfully appreciated
Initialize the variable i with 0 and use comparison instead of assignment in this condition
int i = 0;
//...
if(i == 2){//
Take into account that the first call of strcpy is redundant.
In fact you could do the same without a loop. For example
char a[100] = "Alex:HeyGoodMorning!:1911hrs:0:1012:2017:::";
char *p;
if ((p = strtok(a, ":")) && (p = strtok(NULL, ":")))
{
puts(p);
}
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 5 years ago.
Improve this question
The code which does not work. In function main after initializing variables by the user, it goes to if part and after that crash happens. This program's goal is to impact the repetitive characters in the string. So I decided to have a pointer in a function f1 and the pointer should point to 0th char of the array kar[]
then compare the 0th char to 1st char but the program crashes exactly after the last scanf("%s",kar[1000]).
where is the problem?
#include <stdio.h>
char f1(char* p)
{
int i=0,c=1;
while(*(p+i))
{
if(*p==*(++p))
{
c+=1;
p++;
i++;
continue;
}
else
{
if(c>1)
{
printf("%c%d",*p,c);
}
else
{
printf("%c",*p);
}
}
i++;
}
}
int main()
{
int n,i,m;
char kar[1000];
scanf("%d",&n);
for(i=1;i<=(2*n);++i)
{
scanf("%d",&m);
scanf("%s",kar[1000]);
if(m==1)
{
f1(kar);
}
}
}
This
scanf("%s",kar[1000]);
should trigger a compiler warning, as you pass a char where a char* is expected. You pass the 1001st element of kar (which is out of kar's bounds, BTW). In C array indices start with 0 for the 1st element.
To scan into kar, just pass the address of kar's 1st element.
scanf("%s", &kar[0]);
As arrays get decayed to the address of their 1st element when being passed to a function the following statement is equivalent
scanf("%s", kar);
Please note that the above two statements very well allow the user to enter more characters then kar can hold and with this make scanf() overflow kar, that is write beyond it bounds, invoking undefined behaviour, which might crash your program or whatever ...
To avoid this tell scanf() the maximum to scan by doing:
scanf("%999s", kar);
The maximum for chars a strings can hold in C is always one less then defined as C strings need one more char to have their end marked by a '\0'terminator.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
While compiling the below code, i am getting error
"called object strn is not a function"
tired of this error !! need a solution!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define num 400
int main()
{
char strn[num];
int count;
int a=0,e=0,i=0,o=0,u=0;
printf("enter your string!\n");
gets(strn);
for(count=0;count<strlen(strn);count++)
{
if ( strn(count)=='a' )
{
a++;
}
if (strn(count)=='e')
{
e++;
}
You are trying to use strn as if it's a function: strn(count).
You are presumably trying to access the value at the count index, so you should use strn[count].
The error is quite indicative. You have declared strn as an array of characters.
char strn[num];
And using it as strn(count) which is wrong. The compiler considers it as a function. You should use square brackets [ ] instead of parentheses ( ).
In your code, strn(count) represents a function call to strn() with one argument count. What you need is to use the Array subscripting operator [], not ()
You need to change
strn(count)
to
strn[count]
Also, please consider using fgets() over gets().
The subscript operator uses symbols [] for enclosing index. So for example instead of
strn(count)=='a'
you have to write
strn[count]=='a'
Also function gets is not supported any more by the C Standard because it is an unsafe function. Use instead fgets.
The program can look like
#include <stdio.h>
#include <ctype.h>
#define num 400
int main( void )
{
char strn[num];
char *p;
int a = 0, e = 0, i = 0, o = 0, u = 0;
printf( "Enter your string: " );
fgets( strn, num, stdin );
for ( p = strn; *p != '\0'; ++p )
{
char c = tolower( *p );
switch ( c )
{
case 'a':
a++;
break;
case 'e':
e++;
break;
// and so on...
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
i have got a program to do as my homework. the program is simple. it asks to reverse the digits entered by the user and then print it using while loop. the problem arises when the user enters a number starting with zeroes.
For example:
Enter the number: 0089
The reversed number is : 9800
This is how the output should be. instead i get "98" as the answer.
and thanks in advance.
When asked to do someone else's homework, I like to devise an obtuse and compact way to do it.
void reverseNumber(void)
{
char c;
((c=getchar()) == '\n')? 0 : reverseNumber(), putchar(c);
}
Rather than reading the 0089 input as a numeric value, read it as a character array. This way the zeros won't be removed.
Read the numbers as a string.
And then use atoi() (stdlib.h) to make an integer number out if the string:
/* int atoi (const char *) */
Here is working code that makes exactly what your question requires:
// input: 0321
// output: 1230
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[80] = {0}, temp_str[80] = {0};
int num, i, length = 0, temp_length = 0;
printf("Enter a reversed number (e.g. 0089): ");
scanf("%s", str);
length = strlen(str);
temp_length = length;
printf("string_length: %d\n", length);
for ( i = 0; i < length; i++ ) {
temp_str[i] = str[temp_length - 1];
/* The string length is 4 but arrays are [0][1][2][3] (you see?),
so we need to decrement `temp_length` (minus 1) */
temp_length--;
}
printf("temp_str: %s\n", temp_str);
num = atoi(temp_str);
printf("num: %d\n", num);
return 0;
}