I'm making a little program in C where I would put in a couple of numbers and dots and then delete all the dots (.).
I was thinking about a whileloop but I cannot seem to quite understand what I should do next. So far I got this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0)
{
//?????
}
return 0;
Am I on the right track or should I start differently and not use a while loop at all? I can only find solutions where there is a specific string that is not written by the user, but by the programmer...
Put in an IF to only print characters that aren't a dot. Like the others suggested, you should probably change the gets to fgets as well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0) {
if ( s[k] != '.' ) {
printf("%c", s[k]);
}
k++;
}
printf("\n");
return 0;
}
With a while loop, I'm also worried that if the user puts in a full 30 characters, you won't reach your exit condition. To avoid this problem, a for loop would be better (since you already know the size of the array). However, if you do it this way, you'll also need to initialize your array "s" to be blank.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
for ( k = 0 ; k < 30 ; k++ ) {
if ( s[k] != '.' && s[k] != 0 ) {
printf("%c", s[k]);
}
k++;
}
printf("\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char s[30];
int k=0;
printf("Enter your account number including dots. \n");
gets(s);
printf("Account number without dots:");
while (s[k]!=0)
{
if(s[k] == '.')
s[k] = s[k + 1];
k++;
}
s[k] = '\0';
return 0;
#include <stdio.h>
//remove the specified character from str
char *strrmc(char *str, char ch){
char *from, *to;
from = to = str;
while(*from){
if(*from == ch)
++from;
else
*to++ = *from++;
}
*to = '\0';
return str;
}
int main(int argc, char *argv[]){
char s[30] = "192.169.007";
printf("%s\n", strrmc(s, '.'));//192169007
return 0;
}
Here's one way you might go at it - it's different from how you've started, but can easily be modified. It could be improved on as well, but we can quibble about that in further comments. :)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
/* Take account number in as argument to executable */
int dotless_length = 30;
char dotless[dotless_length];
int k = 0;
int i = 0;
while (argv[1][k] != '\0' && i < dotless_length) {
if (argv[1][k] >= 48 && argv[1][k] <= 57) { /* ascii decimal codes for 0-9 */
dotless[i] = argv[1][k];
i++;
}
else if (argv[1][k] != '.') {
printf("invalid input: %c\n", argv[1][k]);
return 1;
}
k++;
}
dotless[i] = '\0'; /* null-terminate it! */
printf("Account number without dots: %s\n", dotless);
return 0;
}
Then compile with gcc -Wall -o zdotless filename.c and run with
./zdotless 401.863.3000 as an example.
Notes: This may look more harder since it goes into input sanitation (and cleanliness) a little more than your original - e.g.
not assuming that user input consists solely of numbers and periods,
saving the resulting dotless string (for presumable future manipulations?),
having one place to change the length of dotless (a step towards not hardcoding it), and
not being interactive.
When you call an executable, argv is what you've typed, so argv[0] is the executable name (./zdotless), argv[1] is the next argument (401.863.3000 as a string), and so on if there are more arguments. Since argv[1] is the string representation of your dotty input number, argv[1][0] is the first character of it, etc.
Since we're copying to dotless character-by-character rather than using string manipulation, you've got to tack on a null character manually. (That same null character is what you'd loop until reaching, when initially reading the input string.) Other questions?...
Related
this is my first question on stack and I'm beginner in c.I declared a char array a[100]={"this is a test\n2nd test}.Now I'm trying to divide this array and take the two parts before and after \n as separate strings.So I declared a 2d array ab[i][k] and used a for loop to copy the characters to ab[i]. if a[j]=='\n' , I put a NULL character at the current position of ab[i][k] and increment i by 1.But for some reason, both ab[0] and ab[1] are displaying "this is a test" when I used printf to display them.Any help or suggestions would be appreciated.
int i=0;
char a[100],ab[100][100],c;
fputs(a,stdout);
printf("%d ",strlen(a));
for(j=0;j<=strlen(a);j++,k++)
{
if(a[j]=='\n')
{
ab[i][k]='\0';
k=0;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("%s\n",ab[0]);
printf("%s",ab[1]);
You need to set k=-1; when you find \n, since it will be incremented at the top of the loop to 0 when you continue;.
You also need to declare int j, k=0; before the loop, to get your code to compile.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[]) {
int i=0;
char ab[100][100];
char a[100] = "this is a test\n2nd test";
printf("%d \n",strlen(a));
int j, k=0;
for(j=0; j<=strlen(a); j++,k++) {
if(a[j]=='\n') {
ab[i][k]='\0';
k=-1;
i++;
continue;
}
ab[i][k]=a[j];
}
printf("1: %s\n",ab[0]);
printf("2: %s\n",ab[1]);
return 0;
}
23
1: this is a test
2: 2nd test
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
char ar[100] = "this is a test\n2nd test\nfoobar\netc";
char sep[10][100];
int i=0;
char* token = strtok(ar, "\r\n");
while(token != NULL) {
sprintf(sep[i], "%s", token);
printf("string #%02i: `%s`.\n", i, sep[i]);
token = strtok(NULL, "\r\n");
i++;
}
return 0;
}
strtok() splits a string by any of the characters passed as a delimiter (new line and carriage return, in this case) into tokens. Passing a null pointer to the function continues where it last left off. It returns a pointer to the beginning of the token,
sprintf() saves formatted data into a variable handling \0 for you, but you could also use memcpy() or strcpy() if you like.
I'm new to C (and programming) and it's possible that my question can be answered with some basic searching and reading; please point me to an answer to the question if it exists.
Let's say that I want to read a number that can possibly be above 999 from the user. From my experience, if I enter the value 10,000 (including the comma), the program would read the number until the comma and then stop taking input. Thus, the input would be 10 instead of 10000.
How can I make it read '10,000' as if it is 10000?
#include <stdio.h>
#include <stdlib.h>
void RemoveChar(char* Number, char chartoberemoved)
{
char *p, *s;
p = s = Number;
while (*s)//Run until last \r\n
{
if (*s != chartoberemoved)
{
*p++ = *s;
}
/* We always advance s. */
s++;
}
/* We 0-terminate p. */
*p = 0;
}
int main(int argc, char* argv[])
{
char array[32];
if (!argv[1])
return -1;
strcpy(array, argv[1]);
RemoveChar(array, ',');
int num = atoi(array);
printf("%d\n", num);
return 0;
}
Most implementation of scanf and printf on Linux support ' to tell that the number may have a thousands separator:
#include <stdio.h>
#include <locale.h>
int main(int argc, char const *argv[])
{
setlocale(LC_NUMERIC, ""); // set the locale so that "," is a thousands separator
const char* string = "10,000";
float num = 0;
sscanf(string, "%'f", &num);
printf("%f\n", num);
return 0;
}
returns
10000.000000
https://www.systutorials.com/docs/linux/man/3-printf/
use strtok its information and documentation can be found here. link
I'm building a program for reversing a string in visual studio, and while I run the code and enter a word I want to reverse, the program crashes.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(" %s", r, sizeof(r));
d = strlen(r);
for (i=d;i!=0;i--) {
printf("%s",i);
}
return 0;
}
Please note that I tried your program on Linux, so no MS Visual C++ and more specifically no conio.h and gets_s.
There are multiple problems with your program:
Your call to gets_s is incorrect, according to this and this, gets_s is defined as:
char *gets_s(
char *buffer,
size_t sizeInCharacters
);
You are calling it with illegal arguments. Instead of gets_s(" %s", r, sizeof(r)); you need to call it like this:
gets_s(r, 256);
the first parameter is pointer to the string buffer where the gets_s function will store the line from input and the second is the size of the buffer, note that in char r[256] you can store 255 characters and terminating zero (\0).
Your for loop is incorrect instead of for (i=d;i!=0;i--) { you need to do it like this:
for (i=d-1;i>=0;i--) {
now the loop starts from last character instead of \0 and ends when the i < 0 ie. the last print will be when i=0.
And your final mistake is that you are using printf incorrectly instead of printf("%s",i); you need to do:
printf("%c",r[i]);
because you are printing characters: "%c" is for char output and r[i] is i-th character from string r (don't forget that we count from 0).
So, in total this is how the program should look like:
#include <stdio.h>
#include <conio.h> // does not exist on GCC (Linux)
#include <string.h>
main(void) {
char r[256]; // 255 characters + \0
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, 256); // store at most 255 characters + \0
// does not work on GCC (Linux) even with -std=C11
d = strlen(r);
// start from last character and include first
for (i=d-1;i>=0;i--) {
// %c - character, r[i] gets the i-th character from string r
printf("%c",r[i]);
}
return 0;
}
void rev(char *s)
{
char *start, *end;
end = start + strlen(s) - 1;
for (start = s; end > start; ++start, --end) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
Use the fgets function, and also put the reversing code in its own function, like I did. So the final code is
int main()
{
char line[80];
fgets(line, 80, stdin);
/* don't allow empty string */
if (*line == '\0') {
fprintf(stderr, "Empty string is not a string\n");
return 1;
}
/* remove the \n placed by fgets */
remnl(line);
rev(line);
printf("%s\n", line);
return 0;
}
void remnl(char *s) { s[strlen(s) - 1] = 0; }
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, sizeof(r));
d = strlen(r) - 1;
for (i = d; i >= 0; i--) {
printf("%c", r[i]);
}
_getch();
return 0;
}
I am writing a filter that should select all lines having a specified length. I ended up having this code, but I don't know how to specify n. I mean, n (and optionally m) should be replaced by a number of lines in command prompt, but I have no idea how to describe it in the code. I thought of case "%d", but from what I know it's not possible to write it like that. That's the code I have so far:
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int n;
int m;
char line[200];
while(fgets(line,sizeof(line)/sizeof(char), stdin)!=NULL)
{
if(argc>1){
switch(argv[0][0])
{
case 'n':
strlen(line)==n;
break;
case '#n':
strlen(line)<n;
break;
case 'n m':
strlen(line)>=n && strlen(line)<=m;
break;
case 'n#':
strlen(line) > n;
break;
}
printf("%s\n", line);
}}
return 0;
}
Your help would mean a lot to me! I don't really know how to make it work anymore.
I think you should parse the command line outside of your loop. Assuming you are going to require the caller of your program to specify both n and m on the command line, it's a simple matter of grabbing the first two parameters and converting them to integers, and then loop over your stdard input. Something like this:
/* call this minmax.c */
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]) {
int n, m, len;
char line[200];
if (argc < 3) {
printf("Must specify min & max line length.");
return -1;
}
n = atoi(argv[1]);
m = atoi(argv[2]);
while(fgets(line, 200, stdin) != NULL) {
len = strlen(line);
if (len >=n && len <= m)
printf(line);
}
return 0;
}
Assuming you are running on *nix:
cc -ominmax minmax.c
Then call it with the min and max line lengths
./minmax 2 5
This will echo back every line you type that is at least 2 characters, but no more then 5.
I hope I understand well the aim of your desired program and here is the code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i=1,n,m; // n and m are the variable which holds
// the limited length
if(argc>=3)
{
// you need to execute the program with this form
// program.exe n m <file.txt
n=atoi(argv[1]); // get the value of n
m=atoi(argv[2]); // get the value of m
printf("n=%d m=%d\n",n,m);
}
char line[1000]; // this variable will hold each line of the file
while (fgets(line,sizeof(line),stdin)) // fgets used to read
{ //the lines in file till the newline
int length=strlen(line)-1;
// we decrement the length to get rid of
// the newline character
if (length < n)
{
printf("line %d:%s status: < %d\n",i,line,n);
}
else if (length==n)
{
printf("line %d:%s status: = %d\n",i,line,n);
}
else if (length>n && length <=m)
{
printf("line %d:%s status: %d < <= %d\n",i,line,n,m);
}
else
{
printf("line %d:%s status: > %d\n",i,line,m);
}
i++;
}
return 0;
}
In case the code does not fit to your needs I think it is sufficient and can be taken as a support for your exact program as it encompasses everything you need !! Hope it helps !!
It's not something trivial but I would like to know the best way to process multiple outputs, for example:
Input
First line of input will contain a number T = number of test cases. Following lines will contain a string each.
Output
For each string, print on a single line, "UNIQUE" - if the characters are all unique, else print "NOT UNIQUE"
Sample Input
3
DELHI
london
#include<iostream>
Sample Output
UNIQUE
NOT UNIQUE
NOT UNIQUE
So how can I accomplish outputs like that? My code so far is:
int main(int argc, char *argv[])
{
int inputs, count=0;
char str[100];
char *ptr;
scanf("%d",&inputs);
while(inputs-- >0)
{
scanf("%s",str);
for(ptr=str; *ptr!='\0';ptr++)
{
if( *ptr== *(ptr+1))
{
count++;
}
}
if(count>0)
{
printf("NOT UNIQUE");
}
else
{
printf("UNIQUE");
}
}
}
But the above will obviously print the output after each input, but I want the output only after entering all the inputs, if the user enters 3, then the user have to give 3 strings and after the output will be given whether the given strings are unique or not. So I want to know how can I achieve the result given in the problem. Also another thing I want to know is, I am using an array of 100 char, which it can hold a string up to 100 characters, but what do I have to do if I want to handle string with no limit? Just declaring char *str is no good, so what to do?
Hope this helps:
#include <stdio.h>
int main(int argc, char *argv[])
{
int inputs,count=0;
char str[20];
scanf("%d",&inputs);
char *ptr;
char *dummy;
while(inputs-- >0)
{
scanf("%s",str);
for(ptr=str; *ptr!='\0';ptr++)
{
for(dummy=ptr+1; *dummy != '\0';dummy++)
{
if( *ptr== *dummy)
{
count=1;
}
}
if(count == 1)
break;
}
if(count>0)
{
printf("NOT UNIQUE");
}
else
{
printf("UNIQUE");
}
}
}
If you want to save stuff for later use, you must store it somewhere. The example below stores up to 10 lines in buf and then points str to the current line:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* for strlen */
#include <ctype.h> /* for isspace */
int main(int argc, char *argv[])
{
int ninput = 0;
char buf[10][100]; /* storage for 10 strings */
char *str; /* pointer to current string */
int i;
printf("Enter up to 10 strings, blank to and input:\n");
for (i = 0; i < 10; i++) {
int l;
str = buf[i];
/* read line and break on end-of-file (^D) */
if (fgets(str, 100, stdin) == NULL) break;
/* delete trailing newline & spaces */
l = strlen(str);
while (l > 0 && isspace(str[l - 1])) l--;
str[l] = '\0';
/* break loop on empty input */
if (l == 0) break;
ninput++;
}
printf("Your input:\n");
for (i = 0; i < ninput; i++) {
str = buf[i];
printf("[%d] '%s'\n", i + 1, str);
}
return 0;
}
Note the two separate loops for input and output.
I've also rejiggled your input. I'm not very fond of fscanf; I prefer to read input line-wise with fgets and then analyse the line with strtok or sscanf. The advantage over fscanf is that yout strings may contain white-space. The drawback is that you have a newline at the end which you usually don't want and have to "chomp".
If you want to allow for longer strings, you should use dynamic allocation with malloc, although I'm not sure if it is useful when reading user input from the console. Tackle that when you have understood the basics of fixed-size allocation on the stack.
Other people have already pointed you to the error in your check for uniqueness.