Wrong output with scanf function - string

so this is supposedly not a difficult question, but I've been getting this problem a few times when running my code in VS code. I am trying to separate the alphabets and numbers from the string, and I have used the method as follows (in my code) according to what is taught in the book. However, despite having the program running, the output is wrong.
Here is my code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main(){
int weight = 0;
int height = 0;
char wunit[] = "";
char hunit[] = "";
printf("Enter the body weight: ");
scanf("%d%s",&weight,wunit);
printf("Enter the height: ");
scanf("%d%s",&height,hunit);
printf("%d,%s,%d,%s", weight, wunit, height, hunit);
return 0;
}
The thing is,if I type in 20lb for weight, and 30mt for height, what happens is that it gives the output: 20,t,30,mt; which generates this weird ‘t’ instead of lb, and I have no idea why this is the case.
Similarly, when I type 30kg for weight, and 20cm for height. It generates this weird output:30,m,0, cm. The kg becomes a 'm' and the 20 is now a '0'!? Why is that the case? The expected output would be 30,kg,20,cm
I tried simply replacing the strings, but that doesn't solve the problem fundamentally. For instance, (considering when my user puts logical inputs like lb or kg for weight), I tried this substitution and it appears to work, but doesn't fix the issue of making 20 -> 0
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
int main(){
int weight = 0;
int height= 0;
char wunit[] = "";
char hunit[] = "";
char wunit2[] = "lb";
char dummy[] = "t";
printf("Enter the body weight: ");
scanf("%d%s",&weight,wunit);
printf("Enter the height: ");
scanf("%d%s",&height,hunit);
if (strcmp(wunit,dummy)==0){
printf("%d,%s,%d,%s\n", weight, wunit2, height, hunit);
}
//printf("%d,%s,%d,%s", weight, wunit, height, hunit);
return 0;
}
I've also tried running it in codecollab, and it shows this error of "stack smashing detected" after I run it a few times, which got me more confused, what has it to do with this?
Thanks in advance.

wunit is an array of size 1 (it is initialized to "", which in chars looks like {'\0'}). What happens when you try to put lots of characters (say, "lb", which is {'l', 'b', '\0'}) into a memory location that is smaller than it should be?
scanf happily writes as many bytes as needed, smashing anything in its way ("stack-smashing", because wunit and all those local variables are stored on the stack). Try to give scanf more space, say using
char wunit[10] = "";
And never ever use "%s" directly. Limit the maximum of characters that you will allow scanf to place, for example using "%9s" to ensure that at most 9 characters + terminator (10 total) will be read.
This works for me:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int weight = 0;
int height = 0;
char wunit[10] = "";
char hunit[10] = "";
printf("Enter the body weight: ");
scanf("%d%9s",&weight,wunit);
printf("Enter the height: ");
scanf("%d%9s",&height,hunit);
printf("%d,%s,%d,%s", weight, wunit, height, hunit);
return 0;
}
Note: scanf with %s is rightfully considered very dangerous. See https://stackoverflow.com/a/2430310/15472

Related

I'm trying to create a string with n characters by allocating memories with malloc, but I have a problem

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n;
printf("Length? ");
scanf("%d", &n);
getchar();
char* str = (char*)malloc(sizeof(char) * (n+1));
fgets(str,sizeof(str),stdin);
for (int i = 0; i < n; i++)
printf("%c\n", str[i]);
free(str);
}
Process results like this!
Length? 5
abcde
a
b
c
?
(I wanted to upload the result image, but I got rejected since I didn't have 10 reputations)
I can't figure out why 'd' and 'e' won't be showing in the results.
What is the problem with my code??
(wellcome to stackoverflow :) (update #1)
str is a pointer to char instead of a character array therefore sizeof(str) is always 8 on 64-bit or 4 on 32-bit machines, no matter how much space you have allocated.
Demo (compilation succeeds only if X in static_assert(X) holds):
#include <assert.h>
#include <stdlib.h>
int main(void){
// Pointer to char
char *str=(char*)malloc(1024);
#if defined _WIN64 || defined __x86_64__ || defined _____LP64_____
static_assert(sizeof(str)==8);
#else
static_assert(sizeof(str)==4);
#endif
free(str);
// Character array
char arr[1024];
static_assert(sizeof(arr)==1024);
return 0;
}
fgets(char *str, int num, FILE *stream) reads until (num-1) characters have been read
Instead of fgets(str,sizeof(str),stdin) please fgets(str,n+1,stdin)
Fixed version:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
int main(void){
int n=0;
printf("Length? ");
scanf("%d",&n);
getchar();
char *str=(char*)calloc((n+1),sizeof(char));
static_assert(
sizeof(str)==sizeof(char*) && (
sizeof(str)==4 || // 32-bit machine
sizeof(str)==8 // 64-bit machine
)
);
fgets(str,n+1,stdin);
for(int i=0;i<n;++i)
printf("%c\n",str[i]);
free(str);
str=NULL;
}
Length? 5
abcde
a
b
c
d
e

C++11: how to use accumulate / lambda function to calculate the sum of all sizes from a vector of string?

For a vector of strings, return the sum of each string's size.
I tried to use accumulate, together with a lambda function (Is it the best way of calculating what I want in 1-line?)
Codes are written in wandbox (https://wandbox.org/permlink/YAqXGiwxuGVZkDPT)
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> v = {"abc", "def", "ghi"};
size_t totalSize = accumulate(v.begin(), v.end(), [](string s){return s.size();});
cout << totalSize << endl;
return 0;
}
I expect to get a number (9), however, errors are returned:
/opt/wandbox/gcc-head/include/c++/10.0.0/bits/stl_numeric.h:135:39: note: 'std::__cxx11::basic_string' is not derived from 'const __gnu_cxx::__normal_iterator<_Iterator, _Container>'
135 | __init = _GLIBCXX_MOVE_IF_20(__init) + *__first;
I want to know how to fix my codes? Thanks.
That's because you do not use std::accumulate properly. Namely, you 1) did not specify the initial value and 2) provided unary predicate instead of a binary. Please check the docs.
The proper way to write what you want would be:
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> v = {"abc", "def", "ghi"};
size_t totalSize = accumulate(v.begin(), v.end(), 0,
[](size_t sum, const std::string& str){ return sum + str.size(); });
cout << totalSize << endl;
return 0;
}
Both issues are fixed in this code:
0 is specified as initial value, because std::accumulate needs to know where to start, and
The lambda now accepts two parameters: accumulated value, and the next element.
Also note how std::string is passed by const ref into the lambda, while you passed it by value, which was leading to string copy on each invocation, which is not cool

How to get an array of strings without using argv - CS50 pset2

I'm currently doing the CS50 Harvard Course and I'm stuck in problem set 2.
I made this program that takes a name and prints the initials, it takes the name in the command line. How can I use get_string() instead of argv, and argc wich is very unorthodox and sloppy, so I can prompt the user to give me her/his name. Thank you.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
//How do I use Get_string() so I don't have to use argv and argc??
//iterate over strings on the vector (words)
for (int i = 0; i < argc; i++)
{
//prints the 0 character of each string, use "toupper" to convert into capital letters
printf("%c", toupper(argv[i][0]));
}
printf("\n");
}
use Array,
let's say for 10 names
string name[10];
for (int i = 0; i < 10; i++)
{
name[i] = get_string("Enter your name: /n");
}

Simple Cypher Program Not Working (CS50)

On week 2 of CS50 and I've hit a wall. My code is supposed to prompt a user for plaintext and then print a simple cypher on the next line. Problem is, my code keeps printing the exact input for the user rather than scrambling. My code is below.
Note: the error in my code is likely down in the for loop, inside the respective printf functions.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[]){
if (argc != 2){
printf("You must enter two arguments, the second being a single digit integer!\n");
return 1;
}
int key = atoi(argv[1]);
printf("What do you want to encrpyt?");
string s = get_string();
for(int i=0; i < strlen(s); i++){
if (isupper(s[i])==true){
printf("%c",((s[i] + key)));
}
if (islower(s[i])==true){
printf("%c",s[i] + key);
}
else {
printf("%c",s[i]);
}
}
}
Fixed it. The if statement syntax was wrong, so the program was skipping over the cypher text. I need to delete the "==true" out of the if statement.

Why "ls" is not colored after forkpty()

Why output of ls executed here is not colored?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pty.h>
#include <sys/wait.h>
int main(int argc, char **argv ) {
termios termp; winsize winp;
int amaster; char name[128];
if (forkpty(&amaster, name, &termp, &winp) == 0) {
system("ls"); // "ls --color" will work here!
return 0;
}
wait(0);
char buf[128]; int size;
while (1) {
size = read(amaster, buf, 127);
if (size <= 0) break;
buf[size] = 0;
printf("%s", buf);
}
return 0;
}
According to man (and ls.c that I am inspecting) it should be colored if isatty() returns true. After forkpty() it must be true. Besides, ls DOES output in columnized mode in this example! Which means it feels it has tty as output.
Of course I do not want only ls to output color, but an arbitrary program to feel that it has real color enabled tty behind.
I just wrote a simple test:
#include <unistd.h>
int main() {
printf("%i%i%i%i%i\n", isatty(0), isatty(1), isatty(2), isatty(3), isatty(4));
}
and call it in a child part of forkpty, and it displays 11100, which means ls should be colored!
OK, as it seems the fact that ls produces no color output has nothing to do with forkpty(). It is just not color enabled by default. But now, maybe that's another question, why it is not color if it just checks isatty()?

Resources