-
memory violation
Why does this code give memory violation?
#include <stdio.h>
int main(void)
{
char string[80];
char substring[80];
char temp[256];
//int pos = 0;
temp[0] = '\0';
int loc, i, j;
printf("Enter string: ");
scanf("%s",&string);
printf("Enter substring: ");
scanf("%s",&substring);
printf("Enter position: ");
scanf("%d",&loc);
j=0;
for(i=0; i < loc-1; i++)
temp[j++] = string[i];
for(i=0; substring[i] != '\0'; i++)
temp[j++] = substring[i];
for(i=loc-1; string[i] != '\0'; i++)
temp[j++] = string[i];
temp[j] = '\0';
printf("%s",temp);
return 0;
}
-
Code:
scanf("%s",&string);
scanf("%s",&substring);
The name given to an array, is a pointer to the first element of that array. That means that you don't need to use the address of operator (&) with an array, for the call to the scanf() function, like you do with standard identifiers. :)
So change those lines to:
Code:
scanf("%s",string);
scanf("%s",substring);
John.
-
can't enter multi-words...like
Enter string : this is a
can only enter 'a' string..
-
That's a limitation of scanf(). You'll need to read up about the other input/output functions.
http://www.ssec.wisc.edu/~dglo/c_class/stdio.html
John.
-
cin.getline(text,lenght);
-
In C++:
Code:
#include <string>
#include <iostream>
int main(void)
{
string a;
string b;
int pos;
cout << "Enter string: ";
getline(cin, a, '\n');
cout << "Enter substring: ";
getline(cin, b, '\n');
cout << "Enter position: ";
cin >> pos;
if(pos < 0) pos = 0;
if(pos > a.length()) pos = a.length();
a.insert(pos, b);
cout << a << endl;
return 0;
}
-
Code:
#include <string>
#include <iostream>
int main(void)
{
string a;
string b;
int pos;
cout << "Enter string: ";
getline(cin, a, '\n');
cout << "Enter substring: ";
getline(cin, b, '\n');
cout << "Enter position: ";
cin >> pos;
if(pos < 0) pos = 0;
if(pos > a.length()) pos = a.length();
a.insert(pos, b);
cout << a << endl;
return 0;
}
You didn't mean to forget
Code:
using namespace std;
did you??
:D
that would make a lot of difference for a newbie like me!:)
-
Quote:
Originally posted by beginner
You didn't mean to forget
Code:
using namespace std;
did you??
:D
that would make a lot of difference for a newbie like me!:)
Sorry, I forgot.... on my compiler I don't have to tell 'm to use namespace std, it compiles fine without it. So sometimes I foget to add this line to my code. Sorry... :D