#include <bits/stdc++.h>
using namespace std;
int main(){
char a[100];
char c[1];
cin >> a;
c[0] = a[8];
cout << c;
}
input: asdfghjklmn
output: lasdfghjklmn
I don't understand how it does element assignment.
#include <bits/stdc++.h>
using namespace std;
int main(){
char a[100];
char c[1];
cin >> a;
c[0] = a[8];
cout << c;
}
input: asdfghjklmn
output: lasdfghjklmn
I don't understand how it does element assignment.
#include<bits/stdc++.h>
Don't. This header is non-standard, non-portable, leads to terrible compilation times and is all around a bad habit born from "competitive" coding sites that revel in bad habits. #include <iostream>
(i.e., including only what you actually use) would be better in all respects.
using namespace std;
Also considered bad practice. Try to keep your namespace minimal.
int main(){
char a[100];
No. Don't. <string>
exists. char[]
is a C string, a thing of backward compatibility. In C++, a "string" is a std::string
object. There is nothing "elite" about using C constructs in C++ code, just lots of potential errors and mistakes.
char c[1];
cin>>a;
c[0]=a[8];
You do not check that a
actually has a character at that index...
cout<<c;
}
c
is not (and, due to its one-byte size, cannot be) null-terminated, i.e. not a string. Yet cout << c
treats it as one and will keep printing characters from memory until it hits a zero byte; you're looking at undefined behavior. In this case c
sits in memory right before a
, so you see c
and a
printed subsequently, but that is in no way guaranteed. One of those things you completely avoid when actually using the language, i.e. <string>
.
#include <iostream>
#include <string>
int main()
{
std::string a;
std::string c;
std::cin >> a;
if ( a.length() > 8 )
{
c.push_back( a[8] );
}
std::cout << c;
}
There you go.