why I get the result n as the length of first string
// Example program
#include <iostream>
#include <string>
int main()
{
int n = printf("jjj");
printf("%d",n); // jjj3
return 0;
}
thanks a lot
printf returns the number of characaters that have been written, as stated in its manual (printf(3))
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
Hence the 3 in your output. The jjj printed string comes from the first printf call.
int n = printf("jjj"); // prints "jjj"
printf("%d", n); // prints "3" (assuming previous printf did not fail)
printf also return the number of char
Related
I want to display more than one word using printf, Do I should change first parameter in pritnf?
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main() {
int value;
printf("How many:"); scanf("%d", &value);
char* arr1 = new char[value];
scanf("%s[^\n]", arr1);
printf("%s", arr1);
delete [] arr1;
return 0;
}
As already pointed out in the comments section, the following line is wrong:
scanf("%s[^\n]", arr1);
The %s and %[^\n] are distinct conversion format specifiers. You seem to be attempting to use a hybrid of both. If you want to read a whole line of input, you should use the second one.
However, even if you fix this line, your program will not work, for the following reason:
The statement
scanf("%d", &value);
will read a number from standard input, but will only extract the number itself from the input stream. The newline character after the input will not be extracted.
Therefore, when you later call
scanf("%[^\n]", arr1);
it will extract everything that remained from the previous scanf function call up to the newline character. This will result in no characters being extracted if the newline character immediately follows the number (which is normally the case).
Example of program's behavior:
How many:20ExtraInput
ExtraInput
As you can see, everything after the number up to the newline character is being extracted in the second scanf function call (which is then printed). However, this is not what you want. You want to extract everything that comes after the newline character instead.
In order to fix this, you must discard everything up to and including the newline character beforehand. This must be done between the two scanf function calls.
#include <stdio.h>
int main()
{
int value;
int c;
printf("How many:"); scanf("%d", &value);
char* arr1 = new char[value];
//discard remainder of line, including newline character
do
{
c = getchar();
} while ( c != EOF && c != '\n' );
scanf("%[^\n]", arr1);
printf("%s", arr1);
delete [] arr1;
return 0;
}
The program now has the following behavior:
How many:20ExtraInput
This is a test.
This is a test.
As you can see, the program now discards ExtraInput and it correctly echoes the line This is a test.
I am trying to write this c++ program from hackerrank but in my output all I am getting is a blank space.
The input string is in the form of HH:MM:SSpp where HH is an hour on two digits with leading zero, MM the minutes, SS the seconds and pp is either AM or PM.
#include <bits/stdc++.h>
#include<iostream>
#include<string>
using namespace std;
string timeConversion(string s)
{
string p;
int i,j;
if(s[8]==80){ // checking if it is AM or PM
int x = s[0]*10 + s[1] +12;
int y = x%10;
int z = x/10;
s[0]= z;
s[1]= y;
for(i=0;i<10;i++){
p[i]=s[i];
}
}
string newt= p.substr(0, p.size()-2); //removing last two characters
return newt;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
string result = timeConversion(s);
fout << result << "\n";
enter code here
fout.close();
return 0;
}
Is there some logical error? I know the other approach for this question but it would be great if anyone could help me with it.
The problem is with treating character digits (e.g. s[0]) as integer digits.
If you are certain you are dealing with digits, the way to do arithmetic with the characters is by subtracting the value of the character '0', like so: s[0] - '0'. The result will be the integral digit.
The main problem
In your timeConversion() function, you define a string p, which is initialized by the string default constructor to "".
Now for AM times, you skip the if and go directly to string newt= p.substr(0, p.size()-2);, which on an empty p will just create an empty newt string. So you return an empty value. Every time !
For PM times, you go into the if to do some transformations. Unfortunately p[i]=s[i]; doesn't do what you think. In fact it is out of bound access in the empty p string. And in the end, the length of p will still be 0 which will cause an empty value to be returned (in the best case).
The start of a solution
Initialize p at construction:
string p=s;
The code will then immediately work for AM strings. For PM strings, you still need to take into account uv_ 's answer related to ascii vs. binary math.
Here the result:
string timeConversion(string s)
{
string p=s;
int i,j;
if(s[8]=='P'){ // checking if it is AM or PM
int x =(s[0]-'0')*10 + (s[1]-'0') +12;
p[0]= x/10 +'0';
p[1]= x%10 +'0';
}
return p.substr(0, p.size()-2); //removing last two characters
}
Note: this assumes that the entry format will always be valid, and no space will be used instead of a leading 0.
Important Note: This code will fail on hackerrank, because it transforms 12:15:00pm into 24:15:00 and not in 12:15:00. Furthermore 12:00:00am will be tranformed in 12:00:00 instead of 00:00:00. More on wikipedia. Online demo about how to address these special cases
This code will work considering all test cases, just added two more conditions.
string timeConversion(string s)
{
string ans=s;
if(ans[8]=='P')
{
int x = (ans[0]-'0')*10+(ans[1]-'0')+12;
//cout<<x;
if(x!=24)
{
ans[0]=x/10+'0';
ans[1]=x%10+'0';
}
}
if(ans[8]=='A')
{
int y=(ans[0]-'0')*10+ans[1]-'0';
if(y==12)
{
ans[0]='0';
ans[1]='0';
}
}
return ans.substr(0, ans.size()-2);
}
I am trying pull specific characters from a string array, and assign them to defined indices in a new variable. I am having issues with what I expect is the null terminator, as there appear to be random assortment of undefined characters at the end of my strings.
I am new to coding in C++, and lower level programming in general. Note that the function "charBi" works perfectly, but it no longer works when assigning the output of "charBi" to the variable "binar" in the "strBi" function. I realize the code is probably not great, but any help is welcome, especially as it relates to getting rid of the random characters at the end of my "binar" string.
Thanks!
#include <iostream>
#include <array>
using namespace std;
//Program meant to output a string of binary for an input word or phrase
//library of letter and binary pairs
char letterNumber[27][10]={"A01000001","B01000010","C01000011","D01000100","E01000101","F01000110","G01000111",
"H01001000","I01001001","J01001010","K01001011","L01001100","M01001101","N01001110",
"O01001111","P01010000","Q01010001","R01010010","S01010011","T01010100","U01010101",
"V01010110","W01010111","X01011000","Y01011001","Z01011010"," 01011111"};
//finds binary number associated with input character. One character input
string charBi(char inputVar){ //WHY DOES THIS ONLY WORK IF THE FUNCTION IS A STRING?
//loop setup
int n=0;
int last=sizeof(letterNumber)/sizeof(letterNumber[0]); // equal 27
//loops through each of the strings in letterNumber
while (n!=last) {
if (letterNumber[n][0]==inputVar){ // if the letter is equal to input letter
char bina[8]; //number of numbers following a letter
for(int i=1;i<9;i++){ // writes the number associated with the letter to bina
bina[i-1]=letterNumber[n][i]; // assigns number to specific index
}
return bina; //BINA DEFINED AS CHAR, BUT OUTPUTTING AS STRING
}
n++;
}
}
//forms binary string of numbers for input phrase
string strBi(string strg){ //WHY DOES THIS ONLY WORK IF THE FUNCTION IS A STRING?
char binar[8*strg.length()]; //binary for each character is 8 numbers long
for(int i=0;i<strg.length();i++){ // for every letter in the input phrase
string chbi=charBi(strg[i]); //gets binary for individual letter from charBi function
cout<<"charbi sends: "<<chbi<<endl; //for debugging
for(int n=0;n<8;n++){ //for every 1 or 0 in the binary for an idividual letter
binar[(8*i)+n]=chbi[n]; // assign in order to string binar
}
cout<<"binar updates to: "<<binar<<endl; //for debugging
getchar(); //for debugging
}
return binar; //BINAR DEFINED AS CHAR, BUT OUTPUTTING AS STRING
}
int main(){
cout<<"final string is: "<<strBi("HELLO WORLD");
return 0;
}
Since you didn't properly terminate your arrays, the program is undefined.
In order to store a k-letter string, you need to use a k+1-element array and terminate it – char bina[9] = {}; and char binar[8*strg.length() + 1] = {}; should do the trick.
But you can simplify things a bit by leaving C behind:
std::map<char, std::string> letterNumber =
{{'A', "01000001"},
{'B', "01000010"},
// ...
{' ', "01011111}"}};
//forms binary string of numbers for input phrase
std::string strBi(const std::string& strg)
{
std::string binar;
binar.reserve(8 * strg.size());
std::for_each(strg.begin(), strg.end(), [&binar](char c) { binar += letterNumber[c]; });
return binar;
}
Make binar one character longer (char binar [8 * strg.length() + 1];) and set the last character to NUL (just before returning, do binar[8 * strg.length()] = '\0';)
#include <cstdio>
int main()
{
int i;
printf("%d", scanf("%d", &i));
}
Whatever number i input, i get the output:
1
Why is it so?
On success, the scanf function
returns the number of items successfully read.
This count can match the expected number of readings or fewer, even zero, if a matching failure happens.
In the case of an input failure before any data could be successfully read, EOF is returned.
Try this as well:
printf("%d",scanf("%d%d",&i,&i));
You output the result of scanf, which is not the number you enter, but the number of items that are successfully read. The number you enter is stored in i. To output it you would have to write an additional line:
#include <cstdio>
int main()
{
int i;
if (scanf("%d",&i) == 1)
printf("%d", i);
}
scanf() returns the number of items read when it succeeds. Here its reading only one number hence the output is 1 every time regardless of the number.
#include "stdio.h"
#include "conio.h"
int main(void)
{
if(printf("ABC"))
{
}
else
{
printf("XYZ");
}
_getch();
return 0;
}
output : ABC
----------------------------------------------------------------------------------------
#include "stdio.h"
#include "conio.h"
int main(void)
{
if(puts("ABC"))
{
}
else
{
printf("XYZ");
}
_getch();
return 0;
}
output : ABC XYZ
(IDE : MSVC++)
what is the difference between printf and puts in if statement in above 2 programs??
printf returns the number of character written
puts returns a non-negative value in case of success
As a result :
In the first code, printf returns a positive value which evaluates to true, the else branch is never executed, thus printing ABC only
In the second code, puts most likely succeeds and returns 0 which evaluates to false, the else branch gets executed, thus printing both ABC and XYZ
As pointed out by others, puts will also append a newline while printf won't.
puts() appends a newline and returns a different value (non-negative [which could include 0] on success, -1 on failure).
printf returns the number of characters printed (so when successfully printing a non-empty strong, the return value is not 0 and thus true in a boolean context), while puts simply returns a non-negative number to indicate success (which might very well be 0 aka false).
printf on success returns the number of characters written which in your case is 3.
puts on success returns a non-negative number which could also be 0. Looks like it returned a 0 in your case making the else part to execute.