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

问题描述 投票:-1回答:1

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

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

CLion警告

由于函数'operator []'返回const值,因此无法分配给返回值。

type print(const std::string &path){}
c++ const access
1个回答
0
投票

您可以使用

std::string::at 

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

考虑示例

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

希望这会对您有所帮助。


0
投票

如果您真的想按写入的索引访问字符串,则可以使用字符串类方法将其转换为c字符串:

void print(const std::string& path)
{
    if (path.empty()) return;

    // std::cout << path[0] << "\n";
    // or using the range-based-for loop, you could print all the element safely
    for (const char element : path)
        std::cout << element << " ";
}

0
投票

您可以使用

void print(const std::string &path) {
    //convert to c-string, return pointer to c-string:
    const char* temp = path.c_str();
    std::cout << temp[0] << std::endl;
    //and if all you want is just the front character this is a handy method too:
    std::cout << path.front() << std::endl;
}

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

考虑示例

std::string::at 

希望这会对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.