如何打印出常量字符串的第一个元素?

How to print out the first element of a const string?

本文关键字:字符串 第一个 元素 常量 何打印 打印      更新时间:2023-10-16

如何打印出常量字符串的第一个元素?

我试图做 std::cout <<路径[0] <<std::endl; 在 CLion 上 但是路径[0]不起作用,IDE会发出警告。

CLion警告说,

无法赋值,因为函数 'operator[]' 返回常量值。

type print(const std::string &path){}

您可以使用

std::string::at 

它可用于从给定字符串中按字符提取字符。

考虑一个例子

#include <stdio.h>
#include<iostream>
using namespace std;
int main() 
{
string str = "goodday";
cout << str.at(0); 
return 0;
}

希望这对您有所帮助。

首先,您可以忽略警告,有时编译器会抱怨不必要的事情,其次不要执行以下操作:

type print(const std::string &path){}

危险,首先传递字符串作为引用??从编译器的角度来看,字符串是 const 的,每次使用 += 时,您实际上是在创建一个新字符串。但是,如果您将 & 与字符串一起使用,则您正在告诉编译器您计划修改具有 const 类型的字符串对象.....使用字符串路径作为参数,但永远不要使用字符串和路径......