Weird results with post incrementing - post-increment

Ok, I thought i knew about post-incrementing and pre-incrementing but...
Funny /Weird /How? /Why?
#include <stdio.h>
int main()
{
int a = 0;
printf(" A++ - %d \n A++ - %d \n A++ - %d \n A++ - %d", a++, a++, a++, a++);
}
Without compiling it, what would you say the result is (what values would A++ get)?
And what about this?
#include <stdio.h>
int main()
{
int a = 0;
printf(" A++ - %d \n A++ - %d \n A++ - %d \n A++ - %d", a++, a++, a++, ++a);
}
??

Related

C - My code isn't printing the [first] IF statement when I respond with the correct answer - why?

Guessing game: Please guess the correct number from 1-100. However, when the secretNumber is chosen, printf("You got the secret number correct!"); does not execute. Why is this? All other printf statements execute.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int secretNumber = 37;
int guess;
int guessCount = 0;
int guessLimit = 3;
int outOfGuesses = 0;
printf("Enter a number between 1 and 100: ");
/* NOT PRINTING */
scanf("%d", & guess);
guessCount = guessCount + 1;
while (guess != secretNumber && outOfGuesses == 0) {
if (guessCount < guessLimit) {
if (guess == secretNumber) {
printf("You got the secret number correct!");
scanf("%d", & guess);
} else if (guess < secretNumber) {
printf("Enter a higher number: ");
scanf("%d", & guess);
} else if (guess > secretNumber) {
printf("Enter a lower number: ");
scanf("%d", & guess);
}
guessCount = guessCount + 1;
} else {
printf("You are out of guesses.");
}
}
return 0;
}
It is because you brake the while loop before you get to the inner if. You should refactor your code so that the correct number check is done only once, before you print "You got the secret number correct!". Something like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int secretNumber = 37;
int guess;
int guessCount = 0;
int guessLimit = 3;
int outOfGuesses = 0;
printf("Enter a number between 1 and 100: ");
scanf("%d", &guess);
guessCount = guessCount +1;
while (guessCount < guessLimit){
if (guess == secretNumber){
printf("You got the secret number correct!");
break;
}
else if (guess < secretNumber){
printf("Enter a higher number: ");
scanf("%d", &guess);
}
else if (guess > secretNumber){
printf("Enter a lower number: ");
scanf("%d", &guess);
}
guessCount = guessCount + 1;
}
if (guessCount == guessLimit){
printf("You are out of guesses.");
}
return 0;
}

ROS gpsd client Subscriber node (/fix)

I want to write subscriber node for ROS GPSD client which is publishing GPS coordinates on topic "/fix". I don't know exactly what would be the right code and what changes I have to make in CMakeList.txt and package.xml. Below is the code
#include <ros/ros.h>
#include <sensor_msgs/NavSatStatus.h>
#include <sensor_msgs/NavSatFix.h>
using namespace gps_common;
void callback(const sensor_msgs::NavSatFixConstPtr& fix) {
if (fix->status.status == sensor_msgs::NavSatStatus::STATUS_NO_FIX) {
ROS_INFO("No fix.");
return;
}
if (fix->header.stamp == ros::Time(0)) {
return;
}
printf("\n Latitude = %f and Logitude = %f ",fix->latitude, fix->logitude);
}
int main (int argc, char **argv) {
ros::init(argc, argv, "gps_collect");
ros::NodeHandle node;
ros::Subscriber fix_sub = node.subscribe("fix", 10, callback);
ros::spin();
return 0;
}
I have this code working which is in C. Source: https://github.com/felipegutierrez/raspberryExplore/blob/master/src/gps/gpsClient.c
#include <gps.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include "gpsClient.h"
int runGpsStreamClient() {
int rc;
int count = 0;
clock_t t;
struct gps_data_t gps_data;
t = clock();
if ((rc = gps_open("localhost", "2947", &gps_data)) == -1) {
printf("code: %d, reason: %s\n", rc, gps_errstr(rc));
return EXIT_FAILURE;
}
t = clock() - t;
double time_taken = ((double) t) / CLOCKS_PER_SEC; // in seconds
printf("gps_open() took %f seconds to execute \n", time_taken);
t = clock();
gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);
t = clock() - t;
time_taken = ((double) t) / CLOCKS_PER_SEC; // in seconds
printf("gps_stream() took %f seconds to execute \n", time_taken);
while (count < 60) {
/* wait for 1 second to receive data */
if (gps_waiting(&gps_data, 1000000)) {
/* read data */
if ((rc = gps_read(&gps_data)) == -1) {
printf(
"error occurred reading gps data. code: %d, reason: %s\n",
rc, gps_errstr(rc));
} else {
/* Display data from the GPS receiver. */
double lat = gps_data.fix.latitude;
double lon = gps_data.fix.longitude;
double alt = gps_data.fix.altitude;
double speed = gps_data.fix.speed;
double climb = gps_data.fix.climb;
double t = gps_data.fix.time; // EDIT: Replaced tv.tv_sec with gps_data.fix.time
int status = gps_data.status;
int mode = gps_data.fix.mode;
/**
* MODE_NOT_SEEN 0 mode update not seen yet
* MODE_NO_FIX 1 none
* MODE_2D 2 good for latitude/longitude
* MODE_3D 3 good for altitude/climb too
*/
printf("status: %d - ", status);
printf("mode: %d - ", mode);
printf("latitude: %f - ", lat);
printf("longitude: %f - ", lon);
printf("altitude: %f - ", alt);
printf("speed: %f - ", speed);
printf("vertical speed: %f - ", climb);
printf("timestamp: %f - ", t);
printf("%d:%d:%d", (int) (t / 3600), (int) (t / 60), (int) t);
if ((status == STATUS_FIX)
&& (mode == MODE_2D || mode == MODE_3D)
&& !isnan(lat) && !isnan(lon)) {
//gettimeofday(&tv, NULL); EDIT: tv.tv_sec isn't actually the timestamp!
printf(" =) GPS data correctly received\n");
} else {
printf(" =( NO GPS data received\n");
}
}
} else {
printf("Timeout to retrieve data from gpsd.");
}
count++;
sleep(1);
}
/* When you are done... */
gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close(&gps_data);
return EXIT_SUCCESS;
}

xcode jumps a method and finish

im new at coding with Xcode but strangely it jumps some instructions and finish the program without printing the results. the find_track method is not printing the position of the song and skips to end. the code can be build and has "apparently"no error (it comes from a C coding book). Anyone familiar with Xcode who can help ?
char tracks[][80] = {"my spirit","code songs"};
void find_track(char search_for[]) {
int i;
for (i = 0; i < 2; i++){
if (strstr(tracks[i],search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
}
int main()
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}
** Program ended with exit code: 0 // exit message from Xcode
fgets leave newline (enter key) in the buffer. You can easily test it
int main(void)
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
printf("%s", search_for);
for (size_t i=0; i<strlen(search_for); i++)
{
printf ("%X - %c\n", search_for[i], search_for[i]);
}
return 0;
}
Input my spirit from terminal output will be
0x6D - m
0x79 - y
0x20 -
0x73 - s
0x70 - p
0x69 - i
0x72 - r
0x69 - i
0x74 - t
0x0A -
Final 0x0A is '\n' char: newline.
Passing directly it to find_track function strstr will try to match that char too.
So simple solution is to remove that char:
#include <stdio.h>
#include <string.h>
char tracks[][80] = { "my spirit", "code songs" };
void find_track(char search_for[])
{
int i;
for (i = 0; i < 2; i++)
{
if (strstr(tracks[i], search_for) != NULL)
{
printf("Track %i: %s\n", i, tracks[i]);
}
}
}
int main(void)
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
printf("%s", search_for);
// Remove newline
search_for[strlen(search_for)-1] = '\0';
find_track(search_for);
return 0;
}

how to align in printf function

I want to make the printf function print from right to left because this program convert the value of number to binary and I want it to be printed in proper form for example if I convert 16 it is written like that 00001 but it must look like that 10000 so does anyone know how to do that thanks in advance
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,rem;
printf("please enter number: ");
scanf("%d",&x);
while (x !=0)
{
rem=x%2;
if (rem==0)
{
printf("0");
}
else
{
printf("1");
}
x = x/2;
rem = 0;
}
return 0;
}
Here it is:
void print_binary(int x)
{
int skip = 1;
unsigned int mask = 1 << 31;
while(mask > 0){
if(x & mask){
skip = 0;
printf("1");
}else{
if(!skip) printf("0");
}
mask >>= 1;
}
printf("\n");
}
This will print the binary number without trailing zeroes.
If you rather want the result to be stored in a string, you can use:
#include <string.h>
void int_to_binary(int x, char * buff) // buff size must be >= 32 !
{
buff[0] = '\0'; // ensure string ends with \0
unsigned int mask = 1 << 31;
for (; mask > 0; mask >>= 1)
{
strcat(buff, (x & mask) ? "1" : "0");
}
}
To check both codes, use:
int main(int argc, char* argv[])
{
int x;
printf("please enter number: ");
scanf("%d",&x);
char bin[32];
int_to_binary(x, bin);
printf("%s\n", bin);
print_binary(x);
}
What we do is using a mask, which in binary is one "1" beginning on the far left and moving one step right at each loop. The "&" is a bite-wise operator (I let you google it to know how it works). If you need more explanation, feel free to ask.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int binary[20];
int q,i=0;
printf("Enter the decimal no\n");
scanf("%d",&q);
while(q > 0)
{
binary[i]=q%2;
i++;
q=q/2;
}
for(int j=i-1;j>=0;j--)
{
printf("%d",binary[j]);
}
return 0;
}

In Flex when is yylineno updated?

I want to use flex to get the current line number. it seems that flex has a global variable yylineno to keep the current line number when compile.
It is sure that yylineno will increment by 1 when \n is matched. but does ‘r$’ which match a
string at the end of a line change yylineno too? otherwise, are there anyelse situations where yylineno is updated?
For example, I have a source file which is 71 lines in total
/*
Author: guanwanxian
date: 2014-12-29
*/
#include "cstdio"
#include "iostream"
#include "cmath"
#include "tchar.h"
using namespace std;
#define MAX 10000
//This is a struct to represent a Point in two-dimension plane
//Take a test
struct Point{
Point(double XPos_N,double YPos_N){
m_XPos=XPos_N;
m_YPos=YPos_N;
}
double CalDistanceWithAnotherPoint(Point& OtherPoint)
{
double Dis=sqrt((m_XPos-OtherPoint.m_XPos)*(m_XPos-OtherPoint.m_XPos)+(m_YPos-OtherPoint.m_YPos)*(m_YPos-OtherPoint.m_YPos));
return Dis;
}
double m_XPos;
double m_YPos;
};
//this is a function to print Hello World
void PrintHelloWorld()
{
for(int i=0;i<10;i++)
{
printf("Hello World\n");
}
}
/*
this is a function to calculate the sun of two integers
balabala
2014-12-31
*/
int CalSum(int x , int y)
{
int sum=x+y;
return sum;
}
/*
this is the Main function
this is the enterance of my program
this is just a test program
*/
int _tmain(int argc, _TCHAR* argv[])
{
int A=23;
int B=34;
int SumOfAB=CalSum(A,B);
_tprintf(_T("The sum of A and B is:%d \n"),SumOfAB);
PrintHelloWorld();
Point AP(0,0);
Point BP(2,3);
double DisBetAP_AND_BP=AP.CalDistanceWithAnotherPoint(BP);
_tprintf(_T("The distance between AP and BP is:%lf\n"),DisBetAP_AND_BP);
return 0;
}
And my flex file is :
%option noyywrap
%option yylineno
%{
#include <cstdlib>
#include <iostream>
#include "tchar.h"
#include "parser.hpp"
extern int SourceFileLength;//The size of input file
// this function will be generated using bison
extern int yyparse();
int DigitNum=0;
int CommentLineNum=0;
int ProgramLineNum=0;
%}
Digits [0-9]+
BinoOP [-+*/]
parenthesis [()]
%s IN_BLOCK_COMMENT
%s IN_SINGLELINE_COMMENT
%s NOT_COMMENT
%s IN_FUNCTION
%%
<INITIAL>{
"//" {
BEGIN(IN_SINGLELINE_COMMENT);
std::cout<< "enter single line comment\n";
}
"/*" {
std::cout<<"block line num: "<<yylineno<<std::endl;
BEGIN(IN_BLOCK_COMMENT);
std::cout<< "enter block comment\n";
}
([^\/\ \n][^\ \n]*)|(\/[^\*\/\ \n][^\ \n]*)|(\/) { std::cout << yytext <<std::endl;}
\n {std::cout << std::endl; ProgramLineNum++; }
<<EOF>> { std::cout<<"TotalLine: "<<yylineno<<std::endl; std::cout<<"current position: "<<ftell(yyin)<<std::endl; ProgramLineNum++; std::cout<<"File Size: "<<SourceFileLength<<std::endl; return(0);}
. {}
}
<IN_BLOCK_COMMENT>{
"*/" { BEGIN(INITIAL); std::cout << "leave block comment\n" << std::endl; CommentLineNum++; }
[^*\n]+ { std::cout << "BlockLine\n"; }//eat comment in chunks
"*" { std::cout << "\"*\" " << std::endl;}//eat the lone star
"\n" { std::cout <<std::endl; CommentLineNum++; ProgramLineNum++;}
}
<IN_SINGLELINE_COMMENT>{
.*$ { std::cout<<"curretn yyline: "<<yylineno<<std::endl; BEGIN(INITIAL); std::cout<< "SingleLine\n"; std::cout<< "leave single line comment\n"<<std::endl; CommentLineNum++; }//单行注释,包括只有//的情况
}
<NOT_COMMENT>{
}
<IN_FUNCTION>{
BEGIN(INITIAL);
}
The Answer is 75 lines instead of 71 lines. Because the patter .*$ has been matched three times and the initial yylineno seems to be 1, so the answer is 1+71+3=75. am i right?
does r$ which matches a string at end of line change yylineno too?
No.
Smilarly, it is incorrect to increment CommentLineNum in the rule <IN_SINGLE_LINE_COMMENT>.*$. This rule does not consume a line terminator.

Resources