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);
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 3 years ago.
Improve this question
I was solving a problem on strings
Given a string S, write a program to title case every first letter of words in string.
Input:
The first line consists of an integer T i.e number of test cases. T testcases follow. The first and only line of each test case consists of a string S.
Output:
For each testcase, in a new line, print the required output.
Constraints:
1 <= T <= 100
1 <= |S| <= 1000
Example:
Input:
1
I love programming
Output:
I Love Programming
and for that I came up with this solution.
#include <stdio.h>
#include <string.h>
int main() {
//code
int t,flag;
scanf("%d", &t);
while(t--){
int n,i=0;
scanf("%d", &n);
char str[100];
scanf("%s", str);
while(i<n){
if (str[i]!= str[n-1-i]){
flag = 1;
printf("%d", flag);
break;
}
else{
flag = 0;
printf("%d", flag);
continue;
}
i++;
}
if(flag ==1 )
printf("No\n");
else
printf("Yes\n");
}
return 0;
}
This code works fine when continue is removed, but when the above code is run, it prints 0 infinitly.
Can you help me where I'm going wrong?
Thanks in advance.
The "continue" here means "immediately perform the next iteration in the current loop, in this case the while loop".
In your code the line "i++" is therefor not executed and variable i never changes, thus causing an infinite loop.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
So I have this code:
#include <stdio.h>
#include <stdlib.h>
int functie ( int v[], int nr, int z)
{
int i,count;
scanf("%d", &z);
for(i=0;i<nr;i++) {
if(z==v[i]) {
count=count+1;
}
}
return z;
}
int main()
{
int i,nr,z;
fscanf("%d", &z);
FILE *f;
FILE *g;
f=fopen("data-in.txt", "r");
fscanf(f,"%d",&nr);
int *v=malloc(nr*sizeof(int));
for(i=0;i<nr;i++) {
fscanf(f,"%d",&v[i]);
}
g=fopen("data-out.txt", "w");
fprintf(g,"%d %d", functie(v,nr,z));
fclose(f);
fclose(g);
free(v);
}
and before I had int z=0; instead of trying to scanf my var z.
When I run this I get a stopped working error.
I have an array with numbers (integers) read from file, first line is the number of elements and second line the elements.
I need a var lets say z to check how many times an element appears in vector (check if scanned number z is equal to an element and +1 count )
example:
in file
4 (cuz I have 4 elements )
1 2 3 3 ( my elements )
than scan z as 3
z==3 true
count=1
again
count=2
Two issues here, both in main. First:
fscanf("%d", &z);
This function expects a FILE * for the first argument, which you didn't specify. Presumably you wanted to read from the console instead, so use scanf:
scanf("%d", &z);
Second issue:
fprintf(g,"%d %d", functie(v,nr,z));
Your format string is expecting two integer arguments, but you're only passing in one. Get rid of the extra format specifier:
fprintf(g,"%d", functie(v,nr,z));
fscanf will not be delimited by newlines. Best thing to do is eat through file a line at a time with fgets. So, add a line buffer to the top of main:
char line[16]; // assuming integers will actually be small
After opening your file as above with 'f':
if (fgets(line, sizeof(line), f))
{
int count = atoi(line);
int *v = (int *) malloc(count * sizeof(int));
for (int i = 0; i < count && fgets(line, sizeof(line), f); ++i)
{
v[i] = atoi(line);
}
}
You should absolutely add error checking to the above, which is minimal and for concept only (e.g. guard against bad input, buffer overflow, exceptions, count being wrong leaving you uninitialized integers at the end of the array, etc.) as this will only work if your input file is perfect. Note that 16 is generally a ridiculously small length for a line buffer. Also only do your logic against your vector if (a) the file opens, and (b) passes the first test, which is an integral number of entries.
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 was doing homework and when i thought i finally did it fail to work in Visual Studio.
I have code like this and its working perfectly fine in Dev C++, but its not in Visual Studio. Can you explain me why and how to fix it.
Edit: Its compiling in both. In VS its display always 0, and it should 0 for text and a integers and for integers this number.
#include <stdio.h>
#include <string.h>
#include <cstdlib>
#define czy_cyfra( c ) (( c ) > '0' && ( c ) < '9' )
#define jaka_cyfra( c ) (( c ) - '0' )
int czy_liczba_calkowita(char * a)
{
if (*a == '\0')
return -1;
do
{
if (!czy_cyfra(*a))
return -1;
} while (*++a != '\0');
return 0;
}
int jaka_liczba(char * a)
{
int liczba = 0;
do
{
liczba = liczba * 10 + jaka_cyfra(*a++);
} while (*a != '\0');
return liczba;
}
int main()
{
char a[255];
printf("Wprowadz lancuch\n");
scanf_s("%s", a);
printf("%u", czy_liczba_calkowita(a) == 0 ? jaka_liczba(a) : 0);
return 0;
system("pause");
}
You have missed out an argument for scanf_s and this results in undefined behaviour - which may or may not work. It should be
scanf_s("%s", a, (unsigned)sizeof a);
The reason for the unsigned cast? The MSVC man page for scanf_s says
The size parameter is of type unsigned, not size_t.
Not all compilers check that you have supplied arguments for all the fields of XscanXX and XprintXX families. For example, MSVC 9.0 does not check these supposedly "safer" functions for the correct number of arguments, but MSVC 14.0 does, giving a compilation error.
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.
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 a results.txt file and on the seventh line I have numbers in form like:
3 5 6 1 9 7 4
I want to gather information how many of them > 5 and how many of them < 5.
How can I do this process for all of them?
By the way, the seventh line is the last line of the file.
Just read one line at a time and count. When you reach 7, that's your seventh line. Use fgets. Once you have the line you can use strtol in a loop to read each value as an integer.
Reference: fgets, strtol
To skip 1 line in the input file:
fscanf(f, "%*[^\n]\n");
To read 1 number from the file:
int number;
fscanf(f, "%d", &number);
To compare a number with 5:
if (number < 5)
{
...
}
P.S. The site http://www.cplusplus.com has some examples for the basic stuff you need. That site is dedicated to C++ but at your level there so little difference between C and C++, you can use the examples for your work (if you understand them).
Example: fscanf (at the bottom of the page)
#include <stdio.h>
#define LINE_MAX 1024
int main() {
int line_count = 7;
int fd = open('file', r);
int smaller_than_five = 0, bigger_than_five = 0;
int number;
while (line_count != 0) {
fgets(input_line, LINE_MAX, fd);
line_count--;
}
while(sscanf(input_line, "%d", &number) != EOF) {
if (number > 5) bigger_than_five++;
else if (number < 5) smaller_than_five++;
}
/*
* Now you have:
* smaller_than_five which is the count of numbers smaller than five
* bigger_than_five which is the count of numbers bigger than five
*/
return 0;
}
This works when the numbers are on seventh line. If they are on the last (but could be second or 51st), you'll have to change the first while to read while you have not reached the end.