Hello I have a small problem with my C program.
#include<stdio.h>
int main ( int argc, char **argv )
{
char buff[120];
char text;
printf("Enter your name: ");
gets(buff);
text = sprintf(buff, "echo StrText=\"%s\" > spk.vbs");
system(text);
system("echo set ObjVoice=CreateObject(\"SAPI.SpVoice\") >> spk.vbs");
system("echo ObjVoice.Speak StrText >> spk.vbs");
system("start spk.vbs");
return 0;
}
How can I get input from a user and apply it in the system() function?. I am new to C and I am mostly a batch coder, I am trying to port some applications to C so Can anyone tell me to write this application without using the system function?
Thanks in Advance.
Add this to your includes:
#include <string.h>
Change your char text; to char text[120]; - has to be an array, not a single char
Then replace gets with fgets:
fgets(buff, sizeof(buff), stdin); /* for sizeof(buff) to work buff and fgets must be in the same scope */
buff[strlen(buff) - 1] = '\0'; /* this will trim the newline character for you */
Finally you pass text to system after you've formatted it to your purposes (perhaps something like):
sprintf(text, "echo StrText=\"%s\" > spk.vbs", buff);
Is this what you're looking for?
Note: You should also include #include <stdlib.h> for your system call. Always compile with warnings (gcc -Wall -Wextra if you are on Linux), it will be pointed out for you.
Is this what you need?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ( int argc, char **argv )
{
char buff[120];
char text[120];
printf("Enter your command: ");
fgets(buff, sizeof(buff), stdin);
buff[strlen(buff) - 1] = '\0'; /* get rid of the newline characters */
sprintf(text, "echo StrText=\"%s\" > spk.vbs", buff);
system(text);
return 0;
}
gets is deprecated. Use fgets instead.
#include<stdio.h>
int main ( int argc, char **argv )
{
char inputBuf[120];
char cmdBuf[200];
printf("Enter your name: ");
fgets(inputBuf , sizeof( inputBuf) - 1 , stdin );
sprintf(cmdBuf, "echo StrText=\"%s\" > spk.vbs" , inputBuf );
system(cmdBuf);
return 0;
}
Related
This question already has answers here:
To read a line from STDIN to extract the numeric tokens only using C
(2 answers)
Closed 1 year ago.
Lets say I have a buffer and some other pointer for storing the stdin:
char buffer[256];
char *command[3];
And I'm reading from stdin into buffer:
fgets(buffer, BUF_SIZE, stdin);
If stdin was ls -s1, I want to have command[0]="ls" and command[1]="-s1". I also want command[2]=NULL.
For context I am trying to use execvp() later on so I want all the commands separated in command with the null character at the end.
Could someone please let me know how could I go about saving the commands in the command array in that order?
Try this piece of code :
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
int main() {
char buffer[256];
char *command[3];
int i=0;
fgets(buffer,256,stdin);
char *p = strchr(buffer, '\n');
if (p) *p = 0;
char *token=strtok(buffer," ");
command[0]=strdup(token);
printf("%s\n",command[0] );
while(token!=NULL){
token=strtok(NULL," ");
if(token!=NULL){
command[++i]=strdup(token);
printf("%s\n", command[i]);
}
}
command[2]=NULL;
execvp(command[0],command);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main(int args, char* argv[])
{
const int CBUFF = 1024;
char input[CBUFF];
char wkdir[CBUFF];
char* command;
printf("Welcome to MyShell...\n");
while(1)
{
getcwd(wkdir, CBUFF);
printf("%s ? ", wkdir);
fgets(input, CBUFF, stdin);
command = strtok(input, " ");
if(strcmp(command, "cd") == 0)
{
char* path;
path = strtok(NULL, " ");
if(chdir(path) != 0)
{
printf("ERROR: COULD NOT CHANGE DIRECTORY TO SPECIFIED PATH");
}
}
if(strcmp(command, "exit") == 0) break;
}
return 0;
}
I am running into an issue creating a very simple command shell in C. The input is only being read the way I want it too when I add a space after my directive. I know that it has something to do with my improper use of the strtok() function but am not able to figure out what I am doing wrong. I have read the documentation of <string.h> and am turning up blank.
Behavior I want:
Directive "exit" to exit from program.
Current behavior:
Must add space after directive to get it to parse correctly ie. "exit " or "cd " is entered.
You left the trailing newline in the buffer. Get rid of it.
char *got = fgets(input, CBUFF, stdin);
if (!got) return ; /* EOF -- treat like exit */
size_t gotlen = strlen(got);
if (got[gotlen] == '\n') got[gotlen] = 0;
I'm trying to write a program that takes any number of one-word text string arguments, each less than 128 characters long. The program copies text from stdin to stdout, except that any of the words seen in the input are replaced with the word "CENSORED".
Example:
I have this file called poem.txt:
Said Hamlet to Ophelia,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?
The program should do this:
./censor Ophelia < poem.txt
Said Hamlet to CENSORED,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?
Here's my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char lines[200][200];
int numLines=0,i,j;
int nbytes = 128;
int bytes_read=0;
char *my_string;
char * pch;
//reading from stdin
while(stdin)
{
my_string=(char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
strcpy(lines[numLines++],my_string);
}
//scanning and replacing specified words by "CENSORED"
for(i=0;i<argc;i++)
{
for(j=0;j<numLines;j++)
{
pch = strstr (lines[j],argv[i]);
strncpy (pch,"CENSORED",8);
}
}
//display the result in output screen
for(j=0;j<numLines;j++)
{
printf("\n%s",lines[i]);
}
}
The problem is that this is giving segmentation fault, but I can't identify the mistake.
You're not properly overwritting a hit with the replacement which might be longer or shorter -- you're just stuffing it in regardless (potentially overwriting the terminal \0, possibly leading to your segmentation fault). Also, it looks like you miss double hits as you only check each command line word once against each line. Finally, you've made this more complicated by storing all the lines -- no line affects any other so why store them rather than process and print each line in turn?
Here's a overall simplified approach with more detailed replacement code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define REPLACEMENT "CENSORED"
#define BUFFER_SIZE (1024)
int main(int argc, char *argv[])
{
ssize_t bytes_read;
char *s, *line = malloc(BUFFER_SIZE);
size_t nbytes = BUFFER_SIZE, replacement_length = strlen(REPLACEMENT);
// read from stdin
while ((bytes_read = getline(&line, &nbytes, stdin)) != -1)
{
// scanning and replacing specified words
for (int i = 1; i < argc; i++)
{
while ((s = strstr(line, argv[i])) != NULL)
{
size_t search_length = strlen(argv[i]);
size_t tail_length = strlen(s + search_length);
(void) memmove(s + replacement_length, s + search_length, tail_length + 1);
(void) memcpy(s, REPLACEMENT, replacement_length);
}
}
// display the result in output screen
(void) fputs(line, stdout);
}
free(line);
}
Oh yeah, and you forgot to free what you malloc'd. And you're searching for the name of the program as one of your targets...
EXAMPLE
> ./a.out pencil 2B < poem.txt
Said Hamlet to Ophelia,
I'll draw a sketch of thee,
What kind of CENSORED shall I use?
CENSORED or not CENSORED?
I've been looking for a solution to this and haven't found any, I've been trying to make a string that is the size that the user inputs, is there any way to go about doing this? (I'm trying to eliminate null values in the char array).
Edit: I apologize about the missing info, the compiler is gcc -std=c99, and the OS is Ubuntu.
here is the part of the main program that I'm focusing on + the headers (not entirely completed), I'm trying to create a string that is the same length as the user inputs, and that contains the same values.
The compiler currently doesn't recognize myalloc and getline
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
char *string;
int selection, bytes_read, nbytes = 255;
unsigned char key, letter;
do {
...
printf("Enter a sentence:\n");
string = (char *) myalloc(nbytes + 1);
bytes_read = getline(&string, &nbytes, stdin);
...
}while(..);
}
Save the following as main.c:
#define _POSIX_C_SOURCE 200809L
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
int
main()
{
size_t n = 0;
char * line = NULL;
ssize_t count;
printf("Enter a sentence: ");
count = getline(&line, &n, stdin);
if (count < 0)
{
perror("getline");
return EXIT_FAILURE;
}
/* If it bothers you: get rid of the terminating '\n', if any. */
if (line[count - 1] == '\n')
line[count - 1] = '\0';
printf("Your input was: '%s'\n", line);
free(line);
return EXIT_SUCCESS;
}
Then, in a terminal:
$ gcc -o main main.c
$ ./main
Enter a sentence: the banana is yellow
Your input was: 'the banana is yellow'
There is also a more extensive example of using getline included in its man page.
I currently have this program that prints a text file on the console, but every line has an extra new line below it.
if the text was
hello
world
it would output
hello
world
the code is this
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
FILE* fp;
char input[80], ch = 'a';
char key[] = "exit\n";
int q;
fp = fopen("c:\\users\\kostas\\desktop\\original.txt", "r+");
while (!feof(fp)) {
fgets(input, 80, fp);
puts(input);
}
fclose(fp);
return 0;
}
Typically one would use fputs() instead of puts() to omit the newline. In your code, the
puts(input);
would become:
fputs(input, stdout);
puts() adds the newline character by the library specification. You can use printf instead, where you can control what gets printed with a format string:
printf("%s", input);
You can also write a custom puts function:
#include <stdio.h>
int my_puts(char const s[static 1]) {
for (size_t i = 0; s[i]; ++i)
if (putchar(s[i]) == EOF) return EOF;
return 0;
}
int main() {
my_puts("testing ");
my_puts("C puts() without ");
my_puts("newline");
return 0;
}
Output:
testing C puts() without newline
This should work:
#include<stdio.h>
void put_s(char* s){
while(*s) putchar(*s++);
}
Just for the sakes of having more examples, here is another one involving recursion:
#include<stdio.h>
void put_s(char* s){
if(!*s) return;
putchar(*s);
put_s(s+1);
}
Note: I noticed that your code wouldn't compile, because of the #include<iostream> and the using namespace std;.