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 7 years ago.
Improve this question
I am currently learning C as part of a course and I have a task to reverse the order of a number without using any arithmetic (wording of the task).
I currently have this:
#include <stdio.h>
int main()
{
int n, reverse = 0;
printf("Enter a number to reverse\n");
scanf("%d", &n);
while (n != 0) {
reverse = reverse * 10;
reverse = reverse + n_10;
n = n / 10;
}
printf("Reverse of entered number is = %d\n", reverse);
return 0;
}
But this solution uses arithmetic. How can I alter this to complete the task?
From the exercise sheet, "though even at three
digits the naïve approach quickly grows unmanageable with arithmetic (try it!).
Your goal: Design 3-digit solution without using any arithmetic.(Hint: use scanf.)"
The wording of the question was confusing but to be clear the question is:
How do you reverse the order of a number, e.g. 123456789 to 987654321, without without using math. So the solution is to scanf to read the number and swap the numbers in a loop as the answer below.
You can just read it in as a string.
int main()
{
char str[80];
fgets(str, 80, stdin);
strrev(str);
printf("%s\n", str);
}
void strrev(char *str)
{
char *end, tmp;
end = str + strlen(str) - 1;
for (; end > str; --end, ++str) {
tmp = *end;
*end = *str;
*str = tmp;
}
}
I don't know if you consider pointer arithmetic to be "arithmetic"
Read as series of short strings that can hold 1 digit and then print in the reserve order.
char buf[10][2] = { 0 };
scanf("%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]%1[0-9]",
&buf[0], &buf[1], &buf[2], &buf[3], &buf[4],
&buf[5], &buf[6], &buf[7], &buf[8], &buf[9]);
printf("%s%s%s%s%s%s%s%s%s%s",
buf[9], buf[8], buf[7], buf[6], buf[5],
buf[4], buf[3], buf[2], buf[1], buf[0]);
Obviously limited to max 10 digits.
A recusive approach, inpsired by #Nisse Engström. Works for any reasonable length input.
void pr(void) {
char digit[2];
if (scanf("%1[0-9]",digit)) {
pr();
printf("%s",digit);
}
}
int main(void) {
pr();
return 0;
}
Input
012345678901234567890123456789
Output
987654321098765432109876543210
Of course if (scanf("%1[0-9]",digit)) { should be if (scanf("%1[0-9]",digit) == 1) { to cope with EOF but that then may be "arithmetic".
Using scanf():
int
scanf (){
int
stdin =
getchar ();
return
stdin <0||
stdin ==
'\n'?
stdin :(
scanf (),
putchar (
stdin )),
'\n';}
int
main (){
putchar (
scanf ()
);}
Read integer, use sprintf() function to convert it into string and then use the library function strrev() to reverse the string.
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 trying to terminate Integer array input using Enter key. So, I thought of using fgets and sscanf() but I have tried several approaches everytime i am getting first value only. Can someone help where I am doing wrong.
#include<stdio.h>
int main(){
int inp[100]={0};
int c=0,n;
char str[100]={0};
char *data = str;
while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
if (1 != sscanf(str,"%d",&inp[c])) {
puts("Input was not an integer, try again.\n");
continue;
}
printf("\ninp[%d] = %d",c,inp[c]);
c++;
if (c >= 100) break;
}
}
I have added snap of my code and output -
Code
Output
%n is to capture the how many bytes have been read, thus you need to increment data n bytes to point to next number.
The below program reads all the integers till empty new line.
int main() {
int inp[100] = {0};
int c = 0, n = 0;
char str[100] = {0};
char *data = str;
while ((NULL != fgets(str, sizeof str, stdin)) && (str[0] != '\n')) {
data = str;
n = 0;
while (1 == sscanf(data, "%d%n", &inp[c], &n) && c < 100) {
printf("\ninp[%d] = %d\n", c, inp[c]);
data += n;
c++;
}
}
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 4 years ago.
Improve this question
If a user inputted:
1 2 3 4 5 0
How would I transform it into an array with 5 elements (The 0 integer indicates termination)? Also, in the code I need to ensure it works for up to 500 integers.
I have no clue how to proceed. I am thinking of using gets and saving it into an allocated space:
char *ptr;
ptr = malloc(sizeof(char) * 1000);
fgets(ptr, sizeof(char)*1000, stdin);
The problem here is I am not sure how to allocate the space as each digit will be saved as a character and each integer may have different number of digits.
Afterwards, I am not sure how to split it into array.
Could someone advise me on how to continue or if my method is not good?
I know I have not done a lot but I am really confused. I have looked up on gets(), fgets(), scanf(), fscanf(), and am still not sure.
Thanks!
You can parse the line input by the user with sscanf() or strtol():
#include <stdio.h>
int main() {
char buf[256];
int array[5];
if (fgets(buf, sizeof buf, stdin)) {
if (sscanf(buf, "%d%d%d%d%d", &array[0], &array[1], &array[2], &array[3], &array[4]) == 5) {
// array has the 5 numbers input by the user.
printf("%d %d %d %d %d\n", array[0], array[1], array[2], array[3], array[4]);
}
}
return 0;
}
For generic code that works up to 500 numbers, you can just use scanf() in a loop:
#include <stdio.h>
int main() {
int array[500];
int i, n;
for (n = 0; n < 500; n++) {
if (scanf("%d", &array[n]) != 1) {
printf("invalid input\n");
return 1;
}
if (array[n] == 0) {
// 0 indicates termination
break;
}
}
// the array has n valid non-zero numbers
printf("The numbers are:\n");
for (i = 0; i < n; i++) {
printf(" %d\n", array[i]);
}
return 0;
}
You could use a character array with a combination of fgets() and strtok().
First declare a character array str and set a flag variable.
char str[100];
int flag=1;
flag may be made 0 when input 0 is found.
As long as flag is 1 use fgets() to read a line of input (provided fgets() is successful) as in
while(flag==1 && fgets(str, sizeof(str), stdin)!=NULL)
{
.....
.....
}
Now inside this loop, use strtok() to tokenize the string in str using space and \n as delimiters. \n is made a delimiter because fgets() reads in the trailing \n to str as well.
for(ptr=strtok(str, " \n"); ptr!=NULL; ptr=strtok(NULL, " \n"))
{
n=atoi(ptr);
if(n==0)
{
flag=0;
break;
}
printf("\n%d", n);
}
Convert the tokens produced by strtok() to integers. I used atoi() for brevity but it is not the best way. strtol() might be a good idea. See here.
I would suggest something like this
#include "rlutil.h" //a good library similar to conio.h or it's Linux equivalent but cross-platform. You have to include it manually and download it at github.
int i = 0;
int num = 1;
char input;
int array[255];
for (i = 0; num = 0; i++)
{
input = getchar();
num = input - '0';
array[i] = num;
printf("%i ", num);
}
Just pay attention to the size of the array.
Furthermore you could parse the string you got with fgets with strtok. If you want I can edit this post later and include this variant.
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 does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
The program requires a user to insert a number. Let's say we put 149. Now the program prints every number that has 0 digits in them till the number 149 (Including the number). So it's going to be 10,20,30,40,50,60,70,80,90,100,101...110..140 [Let's say the limit would be till 10000]
I have been trying to do this, but i only added +10 to every one, but that cannot be done >100 where it is 101,102..
Use the function sprintf to convert an integer to a string and then search for the character '0' in the string. If found, then print the number. Here's a simple working program implementing this idea.
#include <stdio.h>
#include <string.h>
#define MAXLEN 50 // max number of digits in the input number
int main(void) {
char buf[MAXLEN + 1]; // +1 for the null byte appended by sprintf
char ch = '0'; // char to be searched for in buf
int i, x;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
if(strchr(buf, ch)) // strchr returns a pointer to ch if found else NULL
printf("%d\n", i);
}
return 0;
}
You can also extract each digit of an integer in the given range and check it for zero. Here's a naive implementation.
#include <stdio.h>
int main(void) {
int i, x;
int r;
if(scanf("%d", &x) != 1) {
printf("Error in reading input.\n");
return -1;
}
for(i = 1; i <= x; i++) {
for(r = i; r > 0; r /= 10) {
if(r%10 == 0) {
printf("%d\n", i);
break;
}
}
}
return 0;
}
The simple approach would be to iterate through all natural numbers up to the target number and testing each of them to see if they have any zero digits. Note that the last digit of a non-negative integer i can be obtained as the remainder from division by the base (i % 10 here). Also remember that integer division in C truncates decimals, e.g., (12 / 10) == 1
As a start, consider to convert each number to char [] and then check whether it contains a '0' or not.
To read on:
How to check if a int var contains a specific number
Count the number of Ks between 0 and N
I think this would be the answer.
int j;
for(int i=1;i<150;i++){
j=i;
while(j>0)
{
if(j%10==0)
{
printf("%d\n",i);
break;
}
else
j=j/10;
}
}