Starting a new line of text in C - c

I only have about 1 week of experience in coding, so I've got a lot to learn. I am currently trying to finish an assignment I have in my C class where I have to write a script that can output *s all around the text Welcome to C Programming.
I have managed to complete the first part of the assignment with the code I wrote below, but I can't seem to figure out how to get the *s above and below the text. There wasn't anything mentioned in my notes or lectures either so I'm pretty lost at the moment.
#include <stdio.h>
int main (void)
{
printf ("** Welcome to C Programming **");
return 0;
}
I work on a Mac if that helps. Thanks to anyone that can help me figure this out.
Edit: I added the new line tag and it's working now! Thank you everyone for your input. I am going to try practicing with all of the methods mentioned after I submit my assignment.

You can use the '\n' escape sequence to represent a newline (i.e. line-break) in your printf calls. Since your IDE/code editor most likely uses a monospaced font it should be pretty easy to align the * characters properly:
printf ("******************************\n");
printf ("** Welcome to C Programming **\n");
printf ("******************************\n");
Or, if you wanted to put the whole thing in a single printf call, you can use the \ character followed by a newline in a string literal to break the representation of the string in your editor over multiple lines:
printf (
"******************************\n \
** Welcome to C Programming **\n \
******************************\n"
);
Or even:
printf ("******************************\n"
"** Welcome to C Programming **\n"
"******************************\n");

There is a character for that. It's called "newline". You can't put it directly in the string because that would create a new line in the source code, but inside quotes in C you can produce it with \n.
Alternatively, instead of printf you could use puts, which prints a new line after the string. For this special case this may even be a better solution, since you are not using any of printf's features (the formatting).

As someone in the comments already mentioned - put the \n (new line character) in the text where you want a new line to occur. E.G.
printf("****\nWelcome to C Programming\n****");
****
Welcome to C Programming
****

#include <stdio.h>
int main (void)
{
printf ("******************************\n");
printf ("** Welcome to C Programming **\n");
printf ("******************************\n");
return 0;
}

Related

Quine Program Example in C [duplicate]

This question already has answers here:
C/C++ program that prints its own source code as its output
(10 answers)
Closed 3 years ago.
In my course slides, I have this example but without much explanation:
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}
I understand what quine programs in general mean but I do not quite understand what's happening in the code above. This is the output I get if I run it:
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";main(){printf(f,34,f,34,10);}
But how is it reproducing its own code? I don't really understand how the output is produced.
Start by writing it out in a way that'll be clearer (not changing anything but the layout):
char*f="char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c";
main()
{
printf(f,34,f,34,10);
}
So we see a main function as we'd expect (it should return an int but you're allowed to get away with not in C; likewise for no function arguments).
And before that, a regular string. It's a funny-looking string, but it is not really that different to char*f="fish";.
Okay, so what if we expand the printf by putting the string in there by hand?
printf("char*f=%c%s%c;main(){printf(f,34,f,34,10);}%c" ,34,f,34,10);
We can see that it's going to print out some guff, and substitute in some values along the way. They are:
First %c : 34 (the ASCII code for " (quotes))
First %s : 'f' (our string, once again)
Second %c : 34 (" again)
Third %c : 10 (the ASCII code for Newline)
Let's substitute those all in then too (though I've replaced the contents of the string with <the string>, and "'s with \"'s to make it actually work as a standalone statement):
main()
{
printf("char*f=\"<the string>\";main(){printf(f,34,f,34,10);}\n");
}
Well look at that! main simply prints out the line we first started with. Hurrah!
Edited to add:
Although I've basically spelled out the answer for you, there is still a puzzle remaining. Consider for yourself why we bother substituting in the 34, f, 34, 10, rather than just putting them directly into the string like I did in my final code.

Asking a user to input their name and outputting their initials in C

I just wanted to start this off by admitting I'm a complete beginner to coding, and that it's not something that comes intuitively to me.
What I'm trying to do is write a simple program that has the user input their full name, and outputs their initials. The logic I'm trying to follow is that since strings in C are just characters in an array, the characters that should be an initial will come after the '\0' value.
I'm not sure if my problem is a problem of logic or translating that logic into working syntax, so any help would be appreciated.
Here is the code in full:
# include <stdio.h>
#include <cs50.h>
#include <string.h>
int main (void)
{
printf ("Please insert your name. \n");
string name = get_string();
//printf ("Your name is %s\n", name);
int x = 0;
char c = name [x];
while (c != '\0')
{
x++;
}
printf ("%c/n", c);
}
I understand it's a complete mess, but again I'm trying to figure out if it's best to just quit, so any help would be appreciated.
Thanks in advance.
The logic I'm trying to follow is that since strings in C are just characters in an array, the characters that should be an initial will come after the '\0' value.
In C, \0 denotes the end of a string, so you definitely don't want to be looking for that value.
Let's think about the logic. Someone's initials are probably:
the first character in the string
the first character after a space
– i.e. "Albus Percival Wulfric Brian Dumbledore" -> "APWBD" –
so you'll want to loop over the string, looking for either:
a space, in which case you'll want to grab the next letter, or
the end of the string ('\0') in which case you'll want to stop.
Edge cases to watch out for:
what happens if the string is empty?
what happens if the string ends with a space? (this might not happen if you're guaranteed to get properly formatted input)
Please don't get discouraged – we were all beginners once. This kind of thinking isn't always straightforward, but the answer will come eventually. Good luck!

Reading spaces on C

I'm trying to read a serie of characters like the following one in C:
&&&&&&&&\n& & & &\n& & &&&& &\n
(notice that in the beginning there are spaces too).
I'm using a cicle "while" with:
scanf("%c",&cvar);
because I'm "storing" the characters into an array of structs that i'm using.
However, the program keeps ignoring the first spaces, and only starts storing from the first '&' appearence.
Any tips? Thank you in advance and sorry for my poor english.
Here is part of the code:
while(scanf("%c",&lab[i].simb)!=EOF){
lab[i].x=x;
lab[i].y=y;
if(lab[i].simb=='\n'){
x=0;
y++;
} else x++;
i++;
}
Read this...
I'll suggest to use getline if you are using gcc, but if however you want to read each character use getc instead of scanf... and sorry for my poor English too...

Creating a Lexical Analyzer in C

I am trying to create a lexical analyzer in C.
The program reads another program as input to convert it into tokens, and the source code is here-
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() {
FILE *fp;
char read[50];
char seprators [] = "\n";
char *p;
fp=fopen("C:\\Sum.c", "r");
clrscr();
while ( fgets(read, sizeof(read)-1, fp) !=NULL ) {
//Get the first token
p=strtok(read, seprators);
//Get and print other tokens
while (p!=NULL) {
printf("%s\n", p);
p=strtok(NULL, seprators);
}
}
return 0;
}
And the contents of Sum.c are-
#include <stdio.h>
int main() {
int x;
int y;
int sum;
printf("Enter two numbers\n");
scanf("%d%d", &x, &y);
sum=x+y;
printf("The sum of these numbers is %d", sum);
return 0;
}
I am not getting the correct output and only see a blank screen in place of output.
Can anybody please tell me where am I going wrong??
Thank you so much in advance..
You've asked a few question since this one, so I guess you've moved on. There are a few things that can be noted about your problem and your start at a solution that can help others starting to solve a similar problem. You'll also find that people can often be slow at answering things that are obvious homework. We often wait until homework deadlines have passed. :-)
First, I noted you used a few features specific to Borland C compiler which are non-standard and would not make the solution portable or generic. YOu could solve the problem without them just fine, and that is usually a good choice. For example, you used #include <conio.h> just to clear the screen with a clrscr(); which is probably unnecessary and not relevant to the lexer problem.
I tested the program, and as written it works! It transcribes all the lines of the file Sum.c to stdout. If you only saw a blank screen it is because it could not find the file. Either you did not write it to your C:\ directory or had a different name. As already mentioned by #WhozCraig you need to check that the file was found and opened properly.
I see you are using the C function strtok to divide the input up into tokens. There are some nice examples of using this in the documentation you could include in your code, which do more than your simple case. As mentioned by #Grijesh Chauhan there are more separators to consider than \n, or end-of-line. What about spaces and tabs, for example.
However, in programs, things are not always separated by spaces and lines. Take this example:
result=(number*scale)+total;
If we only used white space as a separator, then it would not identify the words used and only pick up the whole expression, which is obviously not tokenization. We could add these things to the separator list:
char seprators [] = "\n=(*)+;";
Then your code would pick out those words too. There is still a flaw in that strategy, because in programming languages, those symbols are also tokens that need to be identified. The problem with programming language tokenization is there are no clear separators between tokens.
There is a lot of theory behind this, but basically we have to write down the patterns that form the basis of the tokens we want to recognise and not look at the gaps between them, because as has been shown, there aren't any! These patterns are normally written as regular expressions. Computer Science theory tells us that we can use finite state automata to match these regular expressions. Writing a lexer involves a particular style of coding, which has this style:
while ( NOT <<EOF>> ) {
switch ( next_symbol() ) {
case state_symbol[1]:
....
break;
case state_symbol[2]:
....
break;
default:
error(diagnostic);
}
}
So, now, perhaps the value of the academic assignment becomes clearer.

Learning C (via K&R) using xcode

I'm learning C with The C Programming Language (K&R).
Since I don't particularly want to bob back and forth between a text editor and running gcc, I've decided to use xcode as an IDE. So far, I've been able to follow the book's examples without a problem up until section 1.5.2.
When given the valid (?) program...
#include <stdio.h>
void main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
...I receive no final output telling me how many characters were in my input. I am entering my input via the xcode console window.
Upon some debugging, it looks like my program gets stuck in the while loop, and never encounters the EOF token. To accommodate for this, I've instead substituted a newline as the new condition, by replacing EOF with "\n", which also does nothing and gives me a int to pointer comparison warning.
What am I doing wrong here?
Will I be able to follow K&R using xcode?
Type ^D (control-d) to send an EOF.
If you want to break on a newline, you need to compare the return value of getchar to '\n', not "\n". The former is the actual char value of a newline; the latter is a pointer to a char with that value. If that doesn't make sense to you yet, don't worry, it will once you've read more.

Resources