I'm quite new to C and I was wondering if it is possible to have a variable be defined by an input by the user. I've made a simple prime number counter which shows all the prime numbers from 1 to 100 and I was wondering if there is a library or a code which allows me to define a variable by the user input. Here's my code for better understanding.
#include <stdio.h>
int main(void)
{
for (int i = 2; i < 101; i++) { //I would want the "101" to be a user defined variable
for (int j = 2; j <= i; j++) {
if (i == j) {
printf("%d\n", i);
}
else if (i%j == 0) {
break;
}
}
}
}
Thanks in advance!
#include <stdio.h>
int main(void) {
int num;
scanf("%d",&num); //to take a user input
for (int i=2; i<=num; i++) //I would want the "101" to be a user defined variable
{
for (int j=2; j<=i; j++)
{
if (i == j)
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
Yes, using user input in this way is possible. (It had better be possible! Virtually all programs work on user input.)
In general, there are two main ways of doing it. (1) read from the command line. (2) read from a "file" -- which might just be the user's keyboard.
Let's look at both of these in turn.
1. Read from the command line.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int max;
if(argc <= 1)
{
fprintf(stderr, "usage: %s max\n", argv[0]);
exit(1);
}
max = atoi(argv[1]);
for (int i=2; i<max; i++)
{
for (int j=2; j<=i; j++)
{
if (i == j)
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
To read from the command line, we declare main with two arguments: argc and argv. When main gets called, argc will be a count of how many arguments there are, and argv will contain those arguments. argv is an array of strings, or more precisely, an array of pointers to char, or char *. Also, the first argument will always be the name of the program.
We want the user to type
name_of_the_program 200
to print primes up to 200. So we make sure that the user typed at least one argument, that is, we complain if argc isn't at leaast 2: one for the name of the program, 1 for the argument the user typed. Assuming the user did type an argument, it'll be in argv[1]. (argc[0] is the program name.) The command-line arguments are always passed as strings, but we want a number, an int. So we call atoi to convert the string on the command line (like "200") to an int (like 200).
2. Read from a file.
In this case, the "file" we're going to read from is stdin, the standard input, which by default is the user's keyboard.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int max;
char input_line[100];
printf("How high to go? "); fflush(stdout);
fgets(input_line, 100, stdin);
max = atoi(input_line);
if(max == 0)
{
fprintf(stderr, "try typing a number next time\n");
exit(1);
}
for (int i=2; i<max; i++)
...
We print a prompt to tell the user what we need him to type. We call
fgets(input_line, 100, stdin);
to read one line of input -- that is, we expect the user to type some stuff, then hit RETURN. Since we declared input_line to be an array of 100 characters, it's important that we tell fgets how big it is, so that fgets can be sure not to put more than 100 characters into the array. (That could happen if the user, just to be ornery, typed 100 or more characters before hitting RETURN.)
Similarly to the command line case, we've read input_line as a line of text, a string. So we call atoi again, to convert that string to an int. Also, we make sure that the number is not 0. If the user types "abc" or something, that isn't even a number, atoi will return 0, and we catch that, since we'd never want to try to print prime numbers up to 0.
[P.S. As an alternative to the fgets plus atoi technique I've presented here, another popular method is the scanf function (as illustrated, in fact, in another answer to this question). You can use scanf, and it even seems pretty easy at first, but in the long run it's harder, and there are a bunch of things it doesn't handle at all well. So I recommend learning how to use fgets and friends as soon as you can.]
Related
I have been writing a program to input a phrase and turn it into an acronym. For some reason when I output my acronym at the moment it comes out with a bunch of random characters. How do I fix it?
#include <stdio.h>
#include <string.h>
#define MAXLEN 50
int main() {
int num;
printf("Enter number of acronyms to add to the database:");
scanf("%d", &num);
getchar();
char strings[num][MAXLEN];
char acronym[num][MAXLEN];
for(int i = 0; i < num; i++){
printf("Enter the string to convert into an acronym:");
fgets(strings[i],MAXLEN,stdin);
printf("%s\n", strings[i]);
for(int j = 0; j < 11; j++){
if((strings[i][j]) >= 'A' && (strings[i][j]) <= 'Z'){
char buffer[][20] = {strings[i][j]};
strcat(acronym[i], buffer[i]);
}
}
puts(acronym[i]);
}
return 0;
}
I have tried changing the MAXLEN value to see if it was a memory issue or like a buffer overload. I've also just tried changing around how the strings switch and work together but nothing has worked.
char buffer[][20] = {strings[i][j]};
Here you let the compiler count how many elements the array has from the initialization.
It has 1 element, A string with single a single character strings[i][j] and rest of the 20 byte array filled with 0.
strcat(acronym[i], buffer[i]);
Here you access buffer[i], but there is only one string there (as explained above), so this is invalid if i is anything but 0.
I'm not sure what you are trying to do, but this would be valid implementation of what this code tries to do:
// extract single character as a string
char buffer[2] = {strings[i][j], 0}; // only one of 2 and 0 is mandatory
// append it to acronym
strncat(acronym[i], 20, buffer);
Probably lots of other stuff there is wrong, but here is one definite issue and a possible solution.
Can someone help me with this? I want to write a code that will print random even number "i" times. Here "i" is variable and input (i is always greater than 0). Example: Input (4) I want output to be (4,4,4,4), Input (2) I want output to be (2,2). I want to print the number many times mentioned in the input. Here is the question
Here, the term "random" may not be appropriate.
In order to achieve this, you can:
get the numerical representation of the user input. To do so you can use strtol which returns a number.
use a for-loop print the N occurrences using the standard printf function along with the number formatter %d.
For instance:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int number;
int i;
/* `argc` contains the total number of arguments passed to the
* application. There is always at least one argument (i.e.: the
* application name). Here, we ensure the user has given a argument
* which we expect to be the number (i).
*
* If there are less than two arguments given then the user has
* not passed anything => the command line was "$ ./a.out". */
if (argc < 2) {
goto usage;
}
/* Get the user input number by parsing the user given argument.
* As arguments are string of characters, this function transforms
* the string "1234" into 1234. The result is a number we will be
* able to manipulate (add, sub, mul, div, etc.). */
char *endptr;
number = strtol(argv[1], &endptr, 10);
/* We want to ensure the input was really a number.
* The `strtol` function provides a way to verify whether the
* given string is correctly formatted by giving the last character
* of the string. In case the number is not formatted correctly,
* then the last char is not the NULL terminating char. */
if (*endptr != '\0') {
goto usage;
}
/* Ensure the number is positive. */
if (number < 0) {
goto usage;
}
/* This for loop executes "number" of times. We have a counter
* `i` which value will be incremented from [ 0 to "number" [.
* Each time we execute the loop, we print the number. */
for (i = 0; i < number; i++) {
printf("%d ", number);
}
printf("\n");
return 0;
usage:
// TODO
return 1;
}
The easiest way is to read input from the user and just display the number "n" times. Here's an example:
#include <stdio.h>
int main(int argc, char **argv) {
int user_input, is_correct; // user_input is a number to be displayed
// scanf reads input from the user, %d is an integer
is_correct = scanf("%d", &user_input);
// check if user entered a number
if(!is_correct) {
printf("Incorrect input, enter number!");;
return -1;
}
// check if number is even
if(user_input % 2 != 0) {
printf("Number is not even, try again!");
return -1;
}
// display number
for(int i = 0; i < user_input; ++i) {
printf("%d ", user_input);
}
return 0;
}
the objective of my question is very simple. The first input that I get from the user is n (number of test cases). For each test case, the program will scan a string input from the user. And each of these strings I will process separately.
The question here is how can I get string inputs and process them separately in C language??? The idea is similar to the dictionary concept where we can have many words which are individual arrays inside one big array.
The program I have written so far:
#include <stdio.h>
#define max 100
int main (){
int n; // number of testcases
char str [100];
scanf ("%d\n",&n);
for (int i =0;i <n;i++){
scanf ("%s",&str [i]);
}
getchar ();
return 0;
}
Can someone suggest what should be done?
The input should be something like this:
Input 1:
3
Shoe
Horse
House
Input 2:
2
Flower
Bee
here 3 and 2 are the values of n, the number of test cases.
First of all, Don't be confused between "string" in C++ , and "Character Array" in C.
Since your question is based on C language, I will be answering according to that...
#include <stdio.h>
int main (){
int n; // number of testcases
char str [100][100] ; // many words , as individual arrays inside one big array
scanf ("%d\n",&n);
for (int i =0;i <n;i++){
scanf ("%s",str[i]); // since you are taking string , not character
}
// Now if you want to access i'th word you can do like
for(int i = 0 ; i < n; i++)
printf("%s\n" , str[i]);
getchar ();
return 0;
}
Now here instead of using a two-dimensional array, you can also use a one-dimensional array and separate two words by spaces, and store each word's starting position in some another array. (which is lot of implementation).
First of all yours is not C program, as you can't declare variable inside FOR loop in C, secondly have created a prototype using Pointer to Pointer, storing character array in matrix style datastructure, here is the code :-
#include <stdio.h>
#include <stdlib.h>
#define max 100
int main (){
int n,i; // number of testcases
char str [100];
char **strArray;
scanf ("%d",&n);
strArray = (char **) malloc(n);
for (i =0;i <n;i++){
(strArray)[i] = (char *) malloc(sizeof(char)*100);
scanf ("%s",(strArray)[i]);
}
for (i =0;i <n;i++){
printf("%s\n",(strArray)[i]);
free((strArray)[i]);
}
getchar ();
return 0;
}
#include <stdio.h>
#define MAX 100 // poorly named
int n=0; // number of testcases
char** strs=0;
void releaseMemory() // don't forget to release memory when done
{
int counter; // a better name
if (strs != 0)
{
for (counter=0; counter<n; counter++)
{
if (strs[counter] != 0)
free(strs[counter]);
}
free(strs);
}
}
int main ()
{
int counter; // a better name
scanf("%d\n",&n);
strs = (char**) calloc(n,sizeof(char*));
if (strs == 0)
{
printf("outer allocation failed!")
return -1;
}
for (counter=0; counter<n; counter++)
{
strs[counter] = (char*) malloc(MAX*sizeof(char));
if (strs[counter] == 0)
{
printf("allocate buffer %d failed!",counter)
releaseMemory();
return -1;
}
scanf("%s",&strs[counter]); // better hope the input is less than MAX!!
// N.B. - this doesn't limit input to one word, use validation to handle that
}
getchar();
// do whatever you need to with the data
releaseMemory();
return 0;
}
I've started to write a program that reads and stores team info and stores in a structure, reorders and prints results.
First i'm trying to read team names and stores them in a member in a structure, then read team scores and store them in another member.
However, as soon as i debug the file, it crashes. It doesn't even start correctly. I get this error
Unhandled exception at 0xFEFEFEFE in PA2.exe: 0xC0000005 Access
violation executing location 0xFEFEFEFE.
I've backtracked enough to figure out that it is somewhere in the while loop but can't figure out what's wrong with it.
I am using visual studio 2012 and i get no errors when i build it.
#include "stdafx.h"
#include "string.h"
#include <stdio.h>
struct team
{
char name[20];
int no_games;
int points;
int goals_scored;
int goals_let;
};
int main(void)
{
FILE *input2a;
FILE *input2b;
int error1;
int error2;
int i;
char team1_name[20];
char team2_name[20];
int team1_goals;
int team2_goals;
struct team teamlist[20];
error1 = fopen_s(&input2a, "C:\\Users\\New PC\\Desktop\\input2a.dat", "r");
i = 0;
while (i < 20)
{
i ++;
fscanf_s(input2a, "%s", teamlist[i].name);
}
error2 = fopen_s(&input2b, "C:\\Users\\New PC\\Desktop\\input2b.dat", "r");
while (fscanf_s(input2b, "%s %d %s %d", team1_name, &team1_goals, team2_name, &team2_goals) !=EOF)
{
if (team1_goals < 0)
{
printf("Team %s has negative goals - Invalid entry\n", team1_name);
}
else if (team2_goals < 0)
{
printf("Team %s has negative goals - Invalid entry\n", team2_name);
}
else
{
}
}
return 0;
}
From only looking at the while loop: you write to memory out of bounds.
struct team teamlist[20];
And in the while:
i = 0;
while (i < 20)
{
i ++;
fscanf_s(input2a, "%s", teamlist[i].name);
}
So you enter the while when i=19 and increase it to 20 which makes it out of the bounds for the array.
The problem is here (see my comment):
i = 0;
while (i < 20)
{
i ++; // was 19, become 20, but maximal allowed value is 19
fscanf_s(input2a, "%s", teamlist[i].name);
}
The name of this problem is ABW (array bounds write). It means, that your program writes outside array (it happens when i==19, so the condition of the loop i < 20 is satisfied, but right after it you increase it: i++). To fix it you need just to swap two lines of the body of this loop:
{
fscanf_s(input2a, "%s", teamlist[i].name);
i++;
}
And much better and simplier it would be to use for loop here:
for (i = 0; i < 20; i++)
fscanf_s(input2a, "%s", teamlist[i].name);
And the last fix: now there is still possible ABW error. The reason of it is simple: size of teamlist[i].name is 20. So, if input file contains long lines, your program will write outside this array. To fix it you can extend "%s this way (we have here "19" instead of "20" because last character is '\0'):
for (i = 0; i < 20; i++)
fscanf_s(input2a, "%19s", teamlist[i].name);
And one more thing about fscanf_s(): this function shall return the number of successfully matched and assigned input items. So in the second loop it is better to check, that it returns 4.
Update:
If nothing happens, let's open documentation:
Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size
to be specified for all input parameters of type c, C, s, S, or string
control sets that are enclosed in []. The buffer size in characters is
passed as an additional parameter immediately following the pointer to
the buffer or variable. For example, if you are reading a string, the
buffer size for that string is passed as follows:
char s[10];
scanf_s("%9s", s, _countof(s)); // buffer size is 10, width specification is 9
So in your case in means, that first loop should be corrected this way:
for (i = 0; i < 20; i++)
fscanf_s(input2a, "%19s", teamlist[i].name, _countof(teamlist[i].name));
And you need the same fix for next call of fscanf_s in the second loop, because there are two "%s"s in that call.
I want to store a series of integers till i press an enter in an array.How can i implement that
Input:
1(tab space)2(tab space)3(tab space)4(tab space)enter
i tried doing this
#include<stdio.h>
main()
{
int i,j,c,d;
int a[5];
for(i=0;i<2;i++){
j=0;
while((d=scanf("%d",&c))==1){
a[j]=c;
j=j+1;
}
}
}
I dont know how scanf works and using scanf return value.Please explain how i can store this input if its not impossible to do so with scanf and also
2)What else can be used inside scanf along with %d ?
I have a file with 200 rows with numbers like this
(NOTE: each row has varied number of values but all numbers are less than 200)
1\t2\t3\t4\t5\t
2\t3\t4\t5\t6\t7\t8\t
11\t12\t13\t
.
.
200
... so i have to store this as an adjacency list representation
For the first part of your question. scanf() returns number of elements successfully read but it is of no use here and you can just scan in a loop and scanf() will pick your integers in a line when you press enter.
#include <stdio.h>
int main(void) {
int a[5];
int i, n;
for(i=0;i<5;i++)
{
if(scanf("%d",&a[i]) != 1)
{
printf("Value not read correctly\n");
break;
}
}
n = i;
for(i=0;i<n;i++)
printf("%d\n",a[i]);
return 0;
}
For the second question you have to do something line
1.Read a line from your file using fgets()
2.Break your line using strtok() with tab as delimiter.
3.Now convert each token to integer using atoi()
4.Now do whatever you want with the integer. i.e. create a node add your integer to the node
Let's make some reasonable assumptions about the width of each row.
These assumptions are useful for simple code, though not needed in general.
#define LINE_WIDTH_MAX 1000
#define INTS_PER_LINE_MAX 100
#define ROWS_PER_FILE (200 /* given by OP */)
Read each row with fgets(), then scan. Could use strtol(), sscanf() or various approaches.
This method uses sscanf() and "%n" to determine when the next number might follow.
int row;
for (row = 0; row < ROWS_PER_FILE; row++) {
char buf[LINE_WIDTH_MAX + 2];
if (fgets(buf, sizeof buf, stdin) == NULL) {
break; // Handle EOF or IO error
}
int num[INTS_PER_LINE_MAX];
char *p = buf;
for (int i = 0; i<INTS_PER_LINE_MAX; i++) {
int n = 0;
if (1 != sscanf(p, "%d %n", &num[i], &n)) {
break;
}
p += n;
}
if (*p) Handle_GarbageInLIne();
// do something with the `i` numbers
}
Notes:
Advise never use scanf()/