[英]Not able to print or access last character of a char array in c++
I am trying to store individual character(including the spaces) of a sentence in a char array like "Do or die" but whenever I print the array (char arr) it does not print the last character in the array ie 'e'.我试图将句子的单个字符(包括空格)存储在像“做或死”这样的字符数组中,但是每当我打印数组(字符 arr)时,它都不会打印数组中的最后一个字符,即“e”。
Can somebody tell why is this happening .有人可以告诉为什么会这样。 I am a beginner in c++.
我是 C++ 的初学者。
#include<iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the length of the array\n";
cin >> n;
char arr[n + 1];
cin.ignore(n, '\n');
cout << "Enter the characters of the array\n";
cin.getline(arr, n);
for(int i = 0; i < n; i++)
cout << arr[i] << endl;
return 0;
}
So if you change this cin.getline(arr, n)
to cin.getline(arr, n+1)
this, it will work perfectly.因此,如果您将此
cin.getline(arr, n)
更改为cin.getline(arr, n+1)
this,它将完美运行。
First in C++, the size of an array must be a compile-time constant .So, take for example the following code snippets:首先在 C++ 中,数组的大小必须是编译时常量。因此,以以下代码片段为例:
int n = 10;
int arr[n]; //INCORRECT because n is not a constant expression
The correct way to write the above would be:正确的写法是:
const int n = 10;
int arr[n]; //CORRECT
Similarly, the following(which you did in your code example) is incorrect:同样,以下(您在代码示例中所做的)不正确:
int n;
cout << "Enter the length of the array\n";
cin >> n;
char arr[n + 1]; //INCORRECT
Second the reason you're not getting the last character printed on screen is because the size of you array is n+1
but in your for loop:其次,您没有在屏幕上打印最后一个字符的原因是数组的大小是
n+1
但在您的 for 循环中:
for(int i = 0; i < n; i++)
you're only going upto n.你只会达到 n。 You should replace the above with:
您应该将上述内容替换为:
for(int i = 0; i < n + 1; i++)// note that +1 ADDED HERE
A better solution would be to use std::string
for your purpose as shown below:更好的解决方案是将
std::string
用于您的目的,如下所示:
#include<iostream>
int main()
{
std::string inputString;
std::cout << "Enter the string"<<std::endl;
std::getline(std::cin, inputString);
//first way to print the string
std::cout << inputString << std::endl;
//second way to print the string
for(int i = 0; i < inputString.size(); ++i)
{
std::cout << inputString[i];
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.