#include<stdio.h>
#include<conio.h>
main()
{
char name[25];
printf("Enter Your Full Name:");
int i = 0;
name[i] = getche();
while(name[i] != '\r')
{
i++;
name[i] = getche();
}
printf("\n%s\n", name);
system("pause");
}
On execution when I enter name Razwan Muzaffar I am getting the wrong output. While with some other names the output is Ok. But when I try some other names, makes trouble. Carriage return or buffer memory flush, I think something like is a point of consideration.
I am absolute beginner. So kindly explain the issue.
Related
So i have a problem. I have to separate the first name, last name and hostname of email.
For example:
zephyr.extreme#gmail.com>> Input
Output=
First name= Zephyr
Last name= extreme
Host Name= gmail.com
I am not getting the desired result. I am getting some weird shapes as output.
Code:
#include <stdio.h>
int main()
{
char email[40], first[20],last[20],host[30];
printf("Enter the email= ");
gets(email);
int i;
while(email[i]!='\0')
{
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
while(email[i]!='#')
{
last[i]=email[i];
i++;
}
while(email[i]!='\0')
{
host[i]=email[i];
i++;
}
}
puts(first);
puts(last);
puts(host);
}
Assuming the format will always be first.last#host..., use this code:
#include <stdio.h>
#include <string.h>
int main()
{
char email[40], first[20],last[20],host[30],name[40];
int firstDot,atSymbol;
int i;
int length;
char *token;
printf("Enter the email= ");
gets(email);
length = strlen(email);
for(i=0;i<length;i++){
if(email[i]=='.')
{
firstDot = i;
}
else if(email[i]=='#')
{
atSymbol = i;
}
}
strncpy(name,email,atSymbol);
name[atSymbol]= '\0';
token = strtok(name, ".");
/* walk through other tokens */
while( token != NULL )
{
printf( "%s\n", token );
token = strtok(NULL, ".");
}
strncpy(host,email+atSymbol,length-atSymbol);
host[length-atSymbol] = '\0';
puts(host);
}
So i updated the code, now the only problem is the last output.
After host name= gmail.com prints, but then some extra shapes are also printing. These are smile face and some weird symbols.
Code:
#include <stdio.h>
int main()
{
char email[40], first[20],last[20],host[30];
printf("Enter the email= ");
gets(email);
int i=0,j;
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
i=0;
while(email[i]!='#')
{
last[i]=email[i];
i++;
}
j=i;
i=0;
while(email[j]!='\0')
{
host[i]=email[j];
j++;
i++;
}
printf("First Name= ");
puts(first);
printf("Last name= ");
puts(last);
printf("Host name= ");
puts(host);
}
C strings (char pointers) should be null-terminated. This means your string needs a '\0' character at its end so that string manipulation functions such as puts or strlen know where they end, in constrast to other languages where the string's length is stored together with it. The "weird shapes" you are seeing are just random data stored after the end of the string being interpreted as characters. When you call puts it just keeps outputting bytes-as-characters until it randomly finds a byte with value '\0'
You can solve this by adding a '\0' character to the end of the string after each of the blocks where you write a string.
while(email[i]!='.')
{
first[i]=email[i];
i++;
}
email[i] = '\0'; //same thing as email[i] = 0; but using a char makes what
//you're doing clearer
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *name;
int a;
name=(char *)malloc(sizeof(name));
printf("no. of names:");
scanf("%d",&a);
int i;
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
return 0;
free(name);
}
how to print n numbers of entered string in c am already asked this question but i dont got any proper answer any body known the answer please edit my code please if you run my code its displays last string only i dont know why please help..
You need an array of names. To achieve what you are trying to do you can use either a static array with the maximum size or allocate the memory dinamically as in the following program.
Note that you should also test the return value of malloc... just in case.
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char **name;
int a;
printf("no. of names:");
scanf("%d",&a);
int i;
if( a<=0 )
return 0;
name = (char**)malloc( sizeof(char*)*a);
for(i=0;i<a;i++)
{
printf("enter the name:");
name[i]=(char*)malloc( sizeof(char)*128);
scanf("%s",name[i]);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name[i]);
free(name[i]);
}
free(name);
return(0);
}
Note I had to cast malloc because the compiler that the OP is using raise the error " cannot convert from 'void ' to 'char ** ' " (which means that it's old enough..)
In
name=(char *)malloc(sizeof(name));
name is a char*, so sizeof(name) is the size of an address. Hence you are not allocating enough memory.
Just allocate more memory:
name=(char *)malloc(sizeof(char)*20); //allocating 20 bytes for the block that name will point tor
In addition to wrong space allocation (answered by brokenfoot), you will not get the results you want because you are reading all the names over and over in the same variable name, and later printing the name input last a times:
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
The right approach would be to use an array to store all the names, and later print them one by one. For example:
for(i=0;i<a;i++)
{
printf("Enter the names:")
scanf("%s",name[a]);
}
print("The entered names are: ");
for(i=0;i<a;i++)
{
printf("%s", name[a]);
}
I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.
This is a code that does not work (string argument 2 expected!)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
I don't exactly know what language is that (C++?), but you seem to be passing a char to strcat() instead of a null-terminated string. It's a subtle difference, but strcat will happily access further invalid memory positions until a null byte is found.
Instead of using strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.
Here's my implementation in C:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
I made it return an empty string for the case that repeat == 0 because that's how it works in PHP, according to the online manual.
This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
This prints:
Hello, world!!!!!!!
Convert char to string.
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}
I'm having a slight problem with my code here. I just made a small little program to test to put into my actual program. The idea is to replace all the "(star)here(star)" with the string in the add variable. However, when I run the program my final answer is not exactly correct. These are my results:
I_have_a_star_which is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super prett!
Any ideas on what the problem could be would be much appreciated.
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
cout << temp << endl;
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}
The problem is that you're copying characters into the temp array without initializing it or ever NUL terminating it. So when you call strcat or try to print the contents of temp extra garbage on the end may screw things up. Stick memset(temp, 0, sizeof(temp));
before your while loop or change the declaration to temp[500] = "". Alternately, you could add temp[j] = '\0'; just before the call to strcat and just after then loop.
Dude try this...
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}
I have invalid read of size in the following functions using valgrind. I'm not exactly sure why but if any of you can help me that would be greatly appreciated! From what I can tell it runs okay but there are still some errors that I'm not catching that may even deal with memory allocation and deallocation. Please help!
//alternate constructor that allows for setting of the inital value of the string
MyString::MyString(const char *message)
{
int counter(0);
while(message[counter] != '\0')
{
counter++;
}
Size = counter;
**String = new char [Size];**
for(int i=0; i < Size; i++)
String[i] = message[i];
}
istream& operator>>(istream& input, MyString& rhs)
{
char* t;
int size(256);
t = new char[size];
input.getline(t,size);
**rhs = MyString(t);**
delete [] t;
return input;
}
/*Assignment operator (=) which will copy the source string into the destination string. Note that size of the destination needs to be adjusted to be the same as the source.
*/
MyString& MyString::operator=(const MyString& rhs)
{
if(this != &rhs)
{
delete [] String;
**String = new char[rhs.Size+1];**
Size = rhs.Size;
for(int i = 0; i < Size; i++)
{
** String[i] = rhs.String[i];**
}
}
return *this;
}
Any suggestions?? (All of the problem lines have **)
One thing I see is that your copy constructor doesn't allocate space for \0 and doesn't copy it. Neither does the assignment operator.. Or, if you don't store terminating zero, then why are you looking for it?
and the two implementations differ, why the inconsistency (Size vs counter)?
"From what I can tell it runs okay" - it's called undefined behaviour, or in this case: luck - or, if you like me, and like to catch bugs: a misfortune.